2 October 2009
Simple Geo-location with Google Maps API and jQuery
For a recent project, we needed to generate a point on a map for an event. Without being able to explicitly click on the map to determine the location, we had to write up a quick geo-location script to find a latitude and longitude for the event. This was quite easy with the Google Maps API.
Firstly, you need to include the Google Maps API. You’ll need to replace YOUR_API_KEY with a valid API key for your site.
<script src="http://maps.google.com/maps?file=api&v=2&key=YOUR_API_KEY&sensor=false" type="text/javascript" language="JavaScript" charset="utf-8"></script>
We decided to use a bit of jQuery action to implement this. Here’s the final helper tool we wrote with some simple jQuery effects. I’ve populated the fields with our Seattle address for testing. Have a look at the source code and then come back:
Demo: Simple geo-coding with google maps and jquery
Here’s the bulk of the functionality with a lot of the effects stripped out. First we make sure jQuery is ready to do be used:
// make sure jquery is ready
$(document).ready(function()
{
Inside the ready callback function, instantiate a new instance of the Google geo-coder class:
var geocoder = new GClientGeocoder();
Then extend jQuery to create the geolocateAddress function. This function simply calls the getLocations method of the geocoder class. If there is a response, you can check the Placemark array of the response for your results. Usually–if your address is well formatted–the first item in the array will be your geo-located address:
$.geolocateAddress = function(address)
{
// call the getLocations method of the geocoder class
geocoder.getLocations(address, function(response)
{
if (response != null && response.Placemark != undefined)
{
var placemark = response.Placemark[0];
var coords = placemark.Point.coordinates;
var latLng = new GLatLng(coords[1], coords[0]);
}
else
{
// handle failure here
}
});
}
The important part is checking if the Placemark is set and then generating a latitude/longitude object from the result:
var placemark = response.Placemark[0];
var coords = placemark.Point.coordinates;
var latLng = new GLatLng(coords[1], coords[0]);
To call the code, simply add a hook to a button. In the example, I concatenated an address from the address, city and country fields in the form:
$("#submit").click(function(event)
{
event.preventDefault();
$("#address").attr("disabled", true);
$("#city").attr("disabled", true);
$("#country").attr("disabled", true);
// generate the address
var address = $("#address").val();
address += " " + $("#city").val();
address += " " + $("#country").val();
// call the function with the address
$.geolocateAddress(address);
});
That’s about it. If you’d like to download the demo, it’s located here. Just generate an API key on Google Maps and replace the $api_key variable at the top of the script.


