Geocode with Google Maps API v3

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: , ,

Comments

Popular posts from this blog

C# Crop white space from around the image

Could not load file or assembly 'Microsoft.ReportViewer.Common, Version=xx.0.0.0, Culture=neutral, PublicKeyToken='xxx' or one of its dependencies.

The specified version string contains wildcards, which are not compatible with determinism.