I’ve looked all over the internet for a simple answer to this, but I can’t seem to find one anywhere. I do a simple reverse geocode of a latitude and longitude and I am returned the huge results object. Where do I go from there? Here is what I have so far. Currently zipcode returns “undefined”.
geocoder.geocode( {'latLng' : event.latLng}, function(results, status) {
for(var i; i < results.length; i++){
for(var j=0;j < results[i].address_components.length; j++){
for(var k=0; k < results[i].address_components[j].types.length; k++){
if(results[i].address_components[j].types[k] == "postal_code"){
var zipcode = results[i].address_components[j].short_name;
}
}
}
}
});
This is what I got working. Basically it just does a search for postal code in the first address component, since that contains all the information. Remember, console.log() is your friend.
Edit many years later
Thanks to lovely ES6, supported in move browsers, this can now be done more easily let’s take a look at some easier ways of doing it. First, we could simplify the loop as such
Or we could use the find method