Simple Reverse Geocoding Example
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:
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.
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:
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.

i tried the demo getting i'm near catanzaro - calabria, why not country (ITALY) too?
Or am I missing something?
I think you should make a little modification so we can see a bit of location info in foreignland, Ray :)
Or move to America. We rule.
;)
Thanks for the offer but I'm gonna stay in the UK. Less guns here. We use good old fashioned <a href="http://en.wikipedia.org/wiki/Marquess_of_Queensber...; to protect ourselves :)
For Louis, he had a locality. He did not have a administrative_area_level_1.
How to handle that is a bit up in the air I suppose. His address came out as:
27 Castle Meadow, Norwich, Norfolk NR1 3DS, UK
In a conversation, how would you use that Louis?
Would you say Norwich, Norfolk?
Or Norwhich, UK?
In a conversation to someone in the UK I would say Norwich, Norfolk. Norwich = City, Norfolk = County. If I was talking to someone outside the UK I would say Norwich, UK, or Norwich, England.
Perhaps the logic could be:
1) FIrst try the American way (won't repeat that flow)
2) Then see if locality != admin_area_2 (assuming we have values for both), and if so, render that instead.
Thoughts?
We had a similar thing at work where an address app of electoral information returned things like Building Number, Building Name, Sub-Building Number, Sub-Building Name, Throughfare, Sub-Throughfare and on and on! Bit of a nightmare but once I'd looked at a decent number of addresses I was able to make some rules that got the address right 99% of the time.
var onSuccess = function(position) {
s('lat', position.coords.latitude);
s('long', position.coords.longitude);
var geocoder = new google.maps.Geocoder();
geocoder.geocode( {'location': new google.maps.LatLng(g('lat'),g('long')) },
function(place, status) {
fields = 'name,city,state,country,address,street,route,zip,countie'.split(',');
for( x in fields )
eval( 'var ' + fields[x] + ' = \'\';' );
place = place[0];
name = place.name
for( x=0;x<place.address_components.length;x++ )
{
types = place.address_components[x].types;
sn = place.address_components[x].short_name;
for( y=0;y<types.length;y++ )
{
currentType = types[y];
if( currentType == 'country' )
country = sn;
else if( currentType == 'administrative_area_level_1' )
state = sn;
else if( currentType == 'administrative_area_level_2' )
countie = sn;
else if( currentType == 'locality' )
city = sn;
else if( currentType == 'postal_code' )
zip = sn;
else if( currentType == 'street_number' )
street = sn;
else if( currentType == 'route' )
route = sn;
}
}
for( x in fields )
eval( 's(\'' + fields[x] + '\' = ' + fields[x] + ');' );
});
};
// s and g are just localstorage setitem and getitem alias....
Working fine here in India with chrome browser.
Thank you for sharing your code with us.
I tested your demo from Volos city,
Thessalia- Sterea Ellada region, in Greece
and here are the results:
In Firefox 19.0 it works just fine. The response was
"Hello to you out there in Volos, Thessalia Sterea Ellada!"
In Chrome v. 25 it was also fine, exactly the same response with Firefox.
In Internet Explorer 9, the phrase
"Hello to you out there in" was written in English as in FF and Chrome, but the city and region was written in Greek, but they were also correct !!!
There is no doubt in my mind that maintaining the right to privacy will be one of the biggest issues we face in the 21st century but ultimately location web services are only making it quicker to supply the information we were going to type in anyway ;)
@Carlos - I never said it wasn't good technology. BTW, if I search in Google right now for my favorite pizzeria, it already shows me the closest location in my city. If I click on the map of it in the sidebar you can get the driving directions with one click. So in this case all it will add is the annoying "xxxxx wants to know your location."
My concern is if everybody starts doing this. Do I really need a popup asking me to approve "grandmasjelly in Maine wants to know your location?" No, she doesn't.
Actually I just checked, and Chrome has a setting where you can turn it off completely. There ya go - problem solved. :)
It doesn't matter since I'm probably the only one left on the planet that doesn't like being tracked. I guess I can turn on "Start private browsing" in Chrome which routes all data through Google's servers. Now that's what I call privacy!