Google Geocode via AJAX

I was looking for a quick way to copy and paste an address and get its longitude and latitude, so obviously I looked to Google maps for the answer.
If you have a Google map instantiated you can use it to geocode of an address, with the GClientGeocoder class, but what if you don’t want a map at all?
Of course there is an HTTP API to do it, which seemed a bit more like what I needed.
Here’s a pretty simple class that will make an AJAX request to the Google Geocode API and return the address and longitude and latitude in a standard object, rather than the hierarchical mess that the API itself returns.

function GoogleGeocode(apiKey) {
    this.apiKey = apiKey;
    this.geocode = function(address, callbackFunction) {
        jQuery.ajax({
            dataType: 'jsonp',
            url: 'http://maps.google.com/maps/geo?output=json&oe=utf8&sensor=false'
                    + '&key=' + this.apiKey + '&q=' + address,
            cache: false,
            success: function(data){
                if(data.Status.code==200) {
                    var result = {};
                    var ad = data.Placemark[0].AddressDetails.Country.AdministrativeArea;
                    result.streetAddress = ad.Locality.Thoroughfare && ad.Locality.Thoroughfare.ThoroughfareName ? ad.Locality.Thoroughfare.ThoroughfareName : '';
                    result.city = ad.Locality && ad.Locality.LocalityName ? ad.Locality.LocalityName : '';
                    result.state = ad && ad.AdministrativeAreaName ? ad.AdministrativeAreaName : '';
                    result.zip = ad.Locality.PostalCode && ad.Locality.PostalCode.PostalCodeNumber ? ad.Locality.PostalCode.PostalCodeNumber : '';
                    result.longitude = data.Placemark[0].Point.coordinates[0];
                    result.latitude = data.Placemark[0].Point.coordinates[1];
                    callbackFunction(result);
                } else {
                    callbackFunction(null);
                }
            }
          });
    };
}

As you should have noticed, it uses the jQuery javascript framework. The key piece of information in the class above is dataType: ‘jsonp’ which allows you to get JSON data from another domain, without triggering browser anti-XSS mechanisms.
Below is a simple usage example of the GoogleGeocode class.

var g = new GoogleGeocode('__your_google_api_key__');
var address = jQuery('#address').val();
g.geocode(address, function(data) {
    if(data != null) {
        alert("Street Address: " + data.streetAddress);
    } else {
        alert('ERROR! Unable to geocode address');
    }
});

  GoogleGeocode.js (1.5 KiB, 780 hits)

Comments (5)

ctopher916December 7th, 2009 at 1:52 pm

Thanks Petar. I was having a little bit of trouble with the API. This turned out to be exactly what I needed.

Joe S.January 22nd, 2010 at 3:44 pm

Classic, searching for “google geocode ajax” and stumbled upon this post from my old friend Mr. Strinic. Brilliant little script, BTW. Using it for our Service Center Locator upload tool. Who would’ve thought we’d both end up as web developers back when we were slinging gear at GC Lawndale?

adminFebruary 3rd, 2010 at 9:57 am

Mr Joooooooe S!!!

What are the chances. I guess they are probably a lot better than us meeting in the NBA finals! I’d love to see it when it’s done.

Keep me in the loop.

KaoreMay 25th, 2010 at 9:30 pm

Hi Petar,

Just wrote something similar to auto-complete addresses using gmaps v3: http://tech.cibul.org/geocode-with-google-maps-api-v3/

[...] accomplish the geocoding I found a function on Petar Strinic’s blog, which I modified a bit. Basically, all I wanted to be returned from Google was latitude and [...]

Leave a comment

Your comment