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, 206 hits)
