Using Google Geocoding

November 26, 2011

I wanted to allow my users to search the map, and then show all the brass bands on the map that are within a specific distance of the search location. This is possible by using Google Maps geocoding functionality.

This solution expects to produce a URL in the following format which will render a map and a list of bands that meet the search criteria.

URL Format

/map/search/?location=Leeds&lat=53.7996388&lng=-1.5491220999999769&miles=10

First is the location string searched for. Next comes the latitude and longitude of that point. (The latitude and longitude are used for the actual search, the location is only used for display purposes.) Finally, we have miles, which is the number of miles radius to look for bands in.

JavaScript & HTML

So how do we go about converting Leeds into a latitude and longitude? Step in Google Map's geocoding service.

Our HTML looks like this for the search form:

<p>Search for location 
  <input type="text" name="location" id="location_field" value="{{Location}}" max_length="50" size="20"/> 
  and show bands within 
 <input type="text" name="miles" value="{{Miles}}" id="miles_field" max_length="5" size="5"/> 
 miles 
 [<a href='#' id="search">search</a>]</p>

Values for the Location and Miles are populated via Django's template mechanism.

We then attach a JavaScript handler to the search link, which does the actual work:

gGeocoder = new google.maps.Geocoder();
$('#search').click(function(){
  var lLocation = $('#location_field').val();
  gGeocoder.geocode({
    'address': lLocation
    }, function(pResults, pStatus) {
        if (pStatus === google.maps.GeocoderStatus.OK) {
            var lPosition = pResults[0].geometry.location;
            var lMiles = $('#miles_field').val();
            var lNewUrl = './?location=' + lLocation + "&lat=" + lPosition.lat() + "&lng=" + lPosition.lng() + "&miles=" + lMiles;
            location.replace(lNewUrl);
        } else {
            alert('Could not find geocoordinates for the following reason: ' + pStatus);
        }
    });
});