Cibul Tech Blog - Fiddling with PHP, javascript and things

Posts Tagged ‘Google Maps’

Drag and Drop two Markers linked with a line using Google Maps v3

Friday, July 8th, 2011

In this article we’ll use the google maps v3 API to show two draggable markers on a map linked with a line. As the markers are dragged, we want the line position to be updated so that it appears to always be linked and we also want to an updated indicator displaying the distance between the two markers in kilometers.

To achieve this, we will use the Markers MVCObject properties to bind their positions to a method which will update the line and indicator as the Markers are dragged around the map.

Getting started by creating a Map

We start with an empty html page in which we will write our script. This page shows a full page map with over it a box in which we’ll keep an updated value of the distance between the markers. Here we go:

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Distance widget</title>
    <style type="text/css">
      html, body { height: 100%; margin: 0; padding:0; }
      #map-canvas { height: 100%; width: 100%; }
      #distance-display { position: absolute; bottom: 0; left: 0; width: 100px; height: 20px; z-index: 1; background: white; text-align: center; padding: 10px;}
    </style>
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.2.min.js"></script>
    <script type"text/javascript">
      $(function(){
       
        var map = new google.maps.Map($('#map-canvas'), {
          center: new google.maps.LatLng(48.860932,2.335925),
          zoom: 13,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        });

      });
    </script>
  </head>
  <body>
    <div id="distance-display">distance</div>
    <div id="map-canvas"></div>
  </body>
</html>

With this we have a working full page map ready to receive some markers and a polyline. The libraries we are using are the google maps v3 (obviously) and the jquery library which we use to handle things on the page (like $(‘#map-canvas’)) and also to ensure that the javascript is not executed before the page is fully loaded (that is what the $(function(){}) is for).

Add two markers and a line

Now we add our two markers. One on the Louvre Museum and the second on the Eiffel Tower. Add this after the map declaration:

        var marker = new google.maps.Marker({
          map: map,
          position: new google.maps.LatLng(48.860932,2.335925),
          draggable: true,
          raiseOnDrag: false
        });

        var marker2 = new google.maps.Marker({
          map: map,
          position: new google.maps.LatLng(48.858221,2.29449),
          draggable: true,
          raiseOnDrag: false
        });

We also create the line, which is a Polyline with only two positions, one for each marker:

        var line = new google.maps.Polyline({
          path: [marker.getPosition(), marker2.getPosition()],
          map: map
        });

Calculate the distance between two markers

Before we start binding the markers with the line, we need to be able to calculate the distance between the markers. There used to be a practical method to do this in a previous version the the google maps API but it does not exist in the latest version (last time I checked anyways). So we will add it to the LatLng class so that we can easily determine the distance between two points. This methods uses the Haversine formula to calculate the distance. Add it before the $(function(){… line:

      google.maps.LatLng.prototype.distanceFrom = function(newLatLng) {
        if (newLatLng==undefined) return false;

        var dLat = (newLatLng.lat()-this.lat()) * Math.PI / 180;
        var dLon = (newLatLng.lng()-this.lng()) * Math.PI / 180;
        var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(this.lat() * Math.PI / 180 ) * Math.cos(newLatLng.lat() * Math.PI / 180 )* Math.sin(dLon/2) * Math.sin(dLon/2);
        return 6371000 * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
      }

With this, we can now simply determine the distance between two points. We apply it on the position of our markers at the end of the script:

$('#distance-display').html(Math.round(marker.getPosition().distanceFrom(marker2.getPosition())/10)/100 + ' km');

Here we are calculating the distance, rounding it up to have something in kilometers and we put it in our display

Tie everything up using MVCObject properties

For the time being, everything is initialized, the two markers are displayed with a line in between them, the distance between the two markers is displayed as well at the bottom of the screen, but nothing happens when one of the markers is dragged. What we need is to update the position of the line and update the distance display as the drag occurs. This is where the MVCObject properties of our objects are useful. Using them, we can bind attributes (in our case, the position of the markers) to methods which will update the line position and the distance display any time the attributes are changed.

First we create the method that will update the line and the display (before the $(function(){ again):

      var update_line_and_display = function(line, display, position1, position2){

        // update the line
        line.getPath().setAt(0, position1);
        line.getPath().setAt(1, position2);
       
        // update the display
       
        $(display).html(Math.round(position1.distanceFrom(position2)/10)/100 + ' km');
      }

We want that function to be called whenever the position of the markers change. As markers inherit the MVCObject, their attributes are bound to methods which if defined are triggered any time the attribute is changed. The names of these methods derive from the attribute. In our case, we use the position_changed method for each marker. We add this at the end of the script and we are done!

        marker.position_changed = function() {
          update_line_and_display(line, '#distance-display', this.get('position'), marker2.getPosition());
        }

        marker2.position_changed = function() {
          update_line_and_display(line, '#distance-display', marker.getPosition(), this.get('position'));
        }

You can see it working here.

Tags: , ,
Posted in Uncategorized | 4 Comments »

Geocode with Google Maps API v3

Monday, May 24th, 2010

The purpose of this post is to show how to implement a simple address search tool with auto-completion using Google’s Google Maps API v3 with both client side geocoding and reverse geocoding.

The search menu will propose to search for addresses in two ways: the first will be direct address typing with suggestions for auto-completion and the second will finding addresses by dragging a marker on a map.

address field with autocomplete

See it working here

This is done in 5 steps:

  • create a page and download the jquery libraries
  • initialize a map, a geocoder and a marker
  • setup the jquery search widget to work with the geocoder to fetch suggestions and pin a marker down upon selection of a result
  • configure a listener to reverse geocode marker position when it is being dragged

Create a page

We start by creating a file structure which includes an index.html file, a css/ and a js/ folders. We need as well to go on the jquery website to download the autocomplete widget library as well as the base jquery library. We add a main.css file in the css folder to add some styling later on. Once this is done, edit the html file to include links to the js files, a div for the map, a search field and two fields for latitude and longitude:

<html>
  <head>
    <title>Geocoding with GMap v3</title>
    <link type="text/css" href="css/main.css" rel="stylesheet" />
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
    <script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
    <script type="text/javascript" src="js/jquery-ui-1.8.1.custom.min.js"></script>
    <script type="text/javascript" src="js/main.js"></script>
  </head>
  <body>
    <label>Address: </label><input id="address"  type="text"/>
    <div id="map_canvas" style="width:300px; height:300px"></div><br/>
    <label>latitude: </label><input id="latitude" type="text"/><br/>
    <label>longitude: </label><input id="longitude" type="text"/>
  </body>
</html>

Initialize a map

In the js folder, we create a main.js file in which we will write all of our js code. We start with initializing a map, a geocoder and a marker:

var geocoder;
var map;
var marker;
   
function initialize(){
//MAP
  var latlng = new google.maps.LatLng(41.659,-4.714);
  var options = {
    zoom: 16,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.SATELLITE
  };
       
  map = new google.maps.Map(document.getElementById("map_canvas"), options);
       
  //GEOCODER
  geocoder = new google.maps.Geocoder();
       
  marker = new google.maps.Marker({
    map: map,
    draggable: true
  });
               
}

Instead of launching the initialize function in the onload statement of body, we can execute it once the jquery object is loaded. In main.js we add the statement:

$(document).ready(function() {
         
  initialize();
}

The page should be complete, with a working map and 3 empty fields.

Fetching auto-complete suggestions with the Geocoder

Geocode means figuring out a latitude and longitude pair from an address. We will let the geocoder do that work and we’ll use it to get the results and pin them on the map.

Now that the project is setup, in order to have a working auto-complete field for addresses we need to have two components working together: the jquery autocomplete widget and the google maps API geocode function. Everytime the user types in something in the search field, the autocomplete widget must use the geocoder to fetch a list of suggestions to display.

This is what the autocomplete method enables us to do. It can take quite a few options, but in our application we will only need two:

  1. source: it defines where the data displayed in the autocomplete list comes from (in our case, its the result of the geocoder)
  2. select: it defines what happens when the user selects a result of the list. Here we want it to display a marker on the map

All this comes right after the objects have been initialized:

$(document).ready(function() {
         
  initialize();
                 
  $(function() {
    $("#address").autocomplete({
      //This bit uses the geocoder to fetch address values
      source: function(request, response) {
        geocoder.geocode( {'address': request.term }, function(results, status) {
          response($.map(results, function(item) {
            return {
              label:  item.formatted_address,
              value: item.formatted_address,
              latitude: item.geometry.location.lat(),
              longitude: item.geometry.location.lng()
            }
          }));
        })
      },
      //This bit is executed upon selection of an address
      select: function(event, ui) {
        $("#latitude").val(ui.item.latitude);
        $("#longitude").val(ui.item.longitude);
        var location = new google.maps.LatLng(ui.item.latitude, ui.item.longitude);
        marker.setPosition(location);
        map.setCenter(location);
      }
    });
  });

Try it out. It works but its not too pretty… Add some style to the list box by adding this to the main.css file:

.ui-autocomplete {
    background-color: white;
    width: 300px;
    border: 1px solid #cfcfcf;
    list-style-type: none;
    padding-left: 0px;
}

Reverse Geocoding

This means figuring out the address from a latitude and longitude pair. What we want to do now is to execute a reverse geocoding call when the marker is being dragged on the map and update the address field. This works as well using the geocoder, only instead giving it an address we just give it a latitude longitude pair and it sends back an address if it finds any.

At the end of the js file, we add a on-drag behavior to the marker:

  google.maps.event.addListener(marker, 'drag', function() {
    geocoder.geocode({'latLng': marker.getPosition()}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        if (results[0]) {
          $('#address').val(results[0].formatted_address);
          $('#latitude').val(marker.getPosition().lat());
          $('#longitude').val(marker.getPosition().lng());
        }
      }
    });
  });

Drag and drop the marker and see what happens!

Tags: , ,
Posted in Geolocation | 119 Comments »