Retrieving Postal Code with Google Maps Javascript API V3 Reverse Geocode

Romaine M. picture Romaine M. · Mar 17, 2011 · Viewed 53.4k times · Source

I'm trying to submit a query using the postal code to my DB whenever the googlemaps viewport center changes. I know that this can be done with reverse geocoding with something like:

google.maps.event.addListener(map, 'center_changed', function(){
newCenter();
});
...
function newCenter(){
var newc = map.getCenter();
geocoder.geocode({'latLng': newc}, function(results, status){
if (status == google.maps.GeocoderStatus.OK) {
  var newzip = results[0].address_components['postal_code'];
  }
});
};

Of course, this code doesn't actually work. So I was wondering how I would need to change this in order to extract the postal code from the results array. Thanks

Answer

Tuco picture Tuco · Mar 18, 2011

What I've realized so far is that in most cases the ZIPCODE is always the last value inside each returned address, so, if you want to retrieve the very first zipcode (this is my case), you can use the following approach:

var address = results[0].address_components;
var zipcode = address[address.length - 1].long_name;