Retrieving Postal Code with Google Maps Javascript API V3 Reverse Geocode

59,504

Solution 1

Alright, so I got it. The solution is a little uglier than I'd like, and I probably don't need the last for loop, but here's the code for anyone else who needs to extract crap from address_components[]. This is inside the geocoder callback function

// make sure to initialize i
for(i=0; 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"){
                        zipcode = results[i].address_components[j].short_name;
                    }
                }
            }
    }

Solution 2

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;

Solution 3

You can do this pretty easily using the underscore.js libraray: http://documentcloud.github.com/underscore/#find

_.find(results[0].address_components, function (ac) { return ac.types[0] == 'postal_code' }).short_name

Solution 4

Using JQuery?

var searchAddressComponents = results[0].address_components,
    searchPostalCode="";

$.each(searchAddressComponents, function(){
    if(this.types[0]=="postal_code"){
        searchPostalCode=this.short_name;
    }
});

short_name or long_name will work above
the "searchPostalCode" var will contain the postal (zip?) code IF and only IF you get one from the Google Maps API.

Sometimes you DO NOT get a "postal_code" in return for your query.

Solution 5

$.each(results[0].address_components,function(index,value){
    if(value.types[0] === "postal_code"){
        $('#postal_code').val(value.long_name);
    }
});
Share:
59,504

Related videos on Youtube

Romaine M.
Author by

Romaine M.

Updated on July 09, 2022

Comments

  • Romaine M.
    Romaine M. almost 2 years

    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

  • Romaine M.
    Romaine M. about 13 years
    I hope you're right, maybe I just don't get how you're supposed to interact with the object. If you look at the tutorial thing, it's clear that address_components is an array, and since Javascript doesn't have associative arrays, the only way that I can think to do this is with loops code.google.com/apis/maps/documentation/javascript/…
  • Romaine M.
    Romaine M. about 13 years
    ah, there we go. That's a hell of a lot cleaner. Thanks
  • jpincheira
    jpincheira about 12 years
    thanks buddy, pretty nice one-liner using underscore.js' find()
  • Andy Lobel
    Andy Lobel almost 10 years
    I had to use address.length - 2 Not sure why yours is different?
  • Tuco
    Tuco almost 10 years
    There's a long time since I published this answer, but I remember that in another project I discovered that the index would vary depending on the result. In other words, the zipcode can sometimes not be the last item.
  • Sam Cromer
    Sam Cromer over 9 years
    this doesn't work for me, I am checking the postal code for Iowa City Iowa and it comes up undefined.
  • jmiraglia
    jmiraglia over 9 years
    @Tuco, the index does change. Sometimes it is the last element, others, it is the second to last. Not sure the reason for this though.
  • jmiraglia
    jmiraglia over 9 years
    This should be the approved answer. This works for addresses that do not have the zip code as the last component.
  • Tuco
    Tuco over 9 years
    Indeed @jmiraglia. Long after I published this response, I discovered that for some reason sometimes it's not the last element. Maybe you can validate the value against a Regex, something like /\d{5}-\d{3}/ could to the trick.
  • guinetik
    guinetik over 9 years
    The underscore hack is very good. i'm not using underscore in my current project and i don't feel like adding another lib just for it, but i'm bookmarking this answer :D
  • guinetik
    guinetik over 9 years
    hey @SamCromer i tested the above code and the answer also came undefined. maybe you also forgot to put var i= 0 before the for loop. i added and it worked great!
  • luke_mclachlan
    luke_mclachlan about 9 years
    this works beautifully, just as long as you change 'for(i; i < results.length; i++){' to 'for(i=0; i < results.length; i++){'. many thanks for this solution.
  • miguev
    miguev almost 8 years
    Yes, you do have to go through the array and look for the element that has 'postal_code' in its types array, which may be last or first or anywhere in between.
  • Ashu Ashutosh
    Ashu Ashutosh over 7 years
    With auto complete text box you can get the required Postal address,
  • Guillaume Racicot
    Guillaume Racicot over 7 years
    Please add a bit of explanation with your answer. It might help OP to understand what you are posting here.
  • Ashu Ashutosh
    Ashu Ashutosh over 7 years
    If you want latitude and longitude, just remove the comment part from the two lines mentioned.
  • asprin
    asprin over 7 years
    For those who are wondering why zip code comes at the second last position sometimes, it's because in some cases the last item is the postal_code_suffix key
  • Thanatos11th
    Thanatos11th almost 7 years
    it can also miss if you do not provide enough information, and can lead to error
  • Shubhamoy
    Shubhamoy over 5 years
    I was testing out and for few cases address[address.length - 1] returns the desired zip code while in few cases `address[address.length - 2]. So here is a ternary statement var zipcode = isNaN(address[address.length - 1].long_name) ? address[address.length - 2].long_name : address[address.length - 1].long_name;
  • Rahil Wazir
    Rahil Wazir almost 4 years
    See this answer stackoverflow.com/a/62945561/2264626 with native .find method
  • MadMax
    MadMax over 3 years
    You need a Polyfill for this, cause there is no IE support [caniuse.com/array-find]

Related