Big Data/Analytics Zone is brought to you in partnership with:

Raymond Camden is a developer evangelist for Adobe. His work focuses on web standards, mobile development and Cold Fusion. He's a published author and presents at conferences and user groups on a variety of topics. He is the happily married proud father of three kids and is somewhat of a Star Wars nut. Raymond can be reached via his blog at www.raymondcamden.com or via email at raymondcamden@gmail.com Raymond is a DZone MVB and is not an employee of DZone and has posted 233 posts at DZone. You can read more from them at their website. View Full User Profile

A Simple Example of Reverse Geocoding

03.06.2013
| 3384 views |
  • submit to reddit

Have you ever seen a web site that seemed to know where you were located? I'm not talking about a map, but the actual name of the location? This is done with a process called "Reverse Geocoding." Whereas geocoding refers to translating a human-readable address into a longitude/latitude pair, reverse geocoding is, well, the opposite of that. Given a longitude/latitude pair, what would be the description of that location. In this blog post I'll show a simple example of this process. My example application will attempt to report the city and state you live in.

Once again I'll be making use of Google for my example. One of the services of the Google Maps API is geocoding as well as reverse geocoding. Their reverse geocode API needs a longitude and latitude, we can get that easily enough using Geolocation. Here is a snippet of code that begins the process:

$(document).ready(function() {
 
  //I'm not doing anything else, so just leave
	if(!navigator.geolocation) return;
	
	navigator.geolocation.getCurrentPosition(function(pos) {
		geocoder = new google.maps.Geocoder();
		var latlng = new google.maps.LatLng(pos.coords.latitude,pos.coords.longitude);

Please note that in this demo, if the user doesn't support geolocation I'm not going to do anything else. They won't get an error though and won't know what they are missing.

Once we have the longitude and latitude, we then fire off a request to the geocode service.

geocoder.geocode({'latLng': latlng}, function(results, status) {
	if (status == google.maps.GeocoderStatus.OK) {
        	//we'll do cool crap here
	} 
});

As with our initial geolocation support, all I care about here is a success. If anything goes wrong, I don't care and I just ignore it.

So, here comes the difficult part. The result was from the geocode call is fairly complex. You get an array of results ordered by the quality of the match. If you check the docs, you can see an example of this. Each individual result is also fairly complex. You get an array of address parts that represent, obviously, parts of an address. If you read the "Address Component Types" section of the docs, you can see an explanation of the types of address parts. Each part has one or more of these types applied as a tag.

Based on my reading of the spec, I determined I could get the city when the tag was "locality" and the state when the tag was "administrative_area_level_1." This is US-centric and I've not done any testing yet with other countries.

Given that I knew which tags to look for, I decided to work with the first result and see if I could match those tags:

//Check result 0
var result = results[0];
//look for locality tag and administrative_area_level_1
var city = "";
var state = "";
for(var i=0, len=result.address_components.length; i<len; i++) {
var ac = result.address_components[i];
if(ac.types.indexOf("locality") >= 0) city = ac.long_name;
if(ac.types.indexOf("administrative_area_level_1") >= 0) state = ac.long_name;
}
//only report if we got Good Stuff
if(city != '' && state != '') {
$("#result").html("Hello to you out there in "+city+", "+state+"!");
}

Again, if there isn't a match I don't throw an error. Since this is simply window dressing for the site it doesn't really matter if we don't get a match. Want to see this in action? Check out the demo below.

Published at DZone with permission of Raymond Camden, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)