Reverse Geocoding in Javascript

This was a neat thing I learned recently. We've all done geocoding... pass an address to a web service, like geocoder.us or through the Google Maps API, and get back a coordinate in latitude and longitude, which you can use to search for things nearby (using a database of things with lat/long coordinates and the trusty Haversine Distance formula, get directions, put a marker on a map, etc.)

Recently I've needed to find out a zip code for the person viewing the website. This won't be an exact science, for the obvious reason of desktop computers don't typically have GPS, and IP address geolocating is pretty good for many people but there are those cases where the ISP might assign an IP for Camden to a person in Philadelphia. I have no proof but go along with it. Either way, it will be close enough for what I'm doing.

Basically, all you do is use Google's GeoCoder object, and pass in a google.maps.LatLng object instead an address! Here's how:

var latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var coder = new google.maps.Geocoder();
coder.geocode({ 'latLng': latLng }, showLocaleCallback);


Here's all the code:

function initZip() {
if (navigator.geolocation && typeof (navigator.geolocation.getCurrentPosition) == "function") {
navigator.geolocation.getCurrentPosition(geoCodeCallback);
}
}

function geoCodeCallback(position) {
var latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var coder = new google.maps.Geocoder();
coder.geocode({ 'latLng': latLng }, showLocaleCallback);
}

function showLocaleCallback(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var zip = "";
var res = results[0];
for (var i = 0; i < res.address_components.length; i++) {
if (res.address_components[i].types[0] == "postal_code") {
zip = res.address_components[i].short_name;
}
}

$("[id$=txtZip]").val(zip);
}
}

$(document).ready(initZip);


Be sure to include Google's Map API Javascript and jQuery. These are two cool techs that I really like to work with.

Google's Map API: http://maps.google.com/maps/api/js?sensor=false

Also, if anyone has a pointer on how to more effeciently do this part, I'm all ears:

for (var i = 0; i < res.address_components.length; i++) {
if (res.address_components[i].types[0] == "postal_code") {
zip = res.address_components[i].short_name;
}
}

blog comments powered by Disqus