Geocoding the Contents of an Address Element With jQuery and the Google Maps API

Here’s a little piece of code I put together Friday that will take the contents of an address element and find it’s latitude and longitude using jQuery and the Google Maps API.

var g = new google.maps.Geocoder();
var a = $("#myAddress").text();
a = a.replace( new RegExp( "\\n", "g" ), ' ' );
g.geocode( {address: a}, function(results,status) {
	if (s ==  google.maps.GeocoderStatus.OK) {
		//do some cool mapping stuff
	} else {
		//or fail gracefully in the effort
	}
});

First off, we’ll just assume you’ve already added the proper script includes for the jQuery library and the Google Maps API. If you don’t know how, refer to the individual documentation for each for instructions.

The above code first creates a new instance of the Google Maps Geocoder. Then we use jQuery to retrieve just the text inside an address.We then apply a regular expression to strip out any remaining line feeds, and send off the modified address text to Google using the geocoder object we created. We now have a geocoded lat and long for our address, which we can do all sorts of cool things with. Bazinga!

You don’t need to use jQuery to do grab the address text. You can pick it out using some straightforward DOM manipulation, but jQuery makes it so darned easy. If you’re already using the jQuery library for your project, go the route illustrated above. If you’re not, I don’t think it’s a good return on investment to include the jQuery library just for that. Write a little more code and use native functionality.

There are currently no comments for this post.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>