How to extract Postal code from V3 Google maps API

后端 未结 2 937
伪装坚强ぢ
伪装坚强ぢ 2021-02-04 14:54

I am using the following to get a the lat-lng from a geocode..

  $latitude = $output->results[0]->geometry->location->lat;
  $longitude = $output->         


        
相关标签:
2条回答
  • 2021-02-04 15:40

    I'd say you'd need to loop through results.address_components. On each iteration check if the types array contains "postal_code". If it does, save that to a variable, and probably break out of the loop as well. Although it might be worth investigating to see if the postal_code is always in address_component[5], which would save you having to loop.

    0 讨论(0)
  • 2021-02-04 15:41

    You could use the following function to extract any address component:

    function extractFromAdress(components, type){
        for (var i=0; i<components.length; i++)
            for (var j=0; j<components[i].types.length; j++)
                if (components[i].types[j]==type) return components[i].long_name;
        return "";
    }
    

    To extract the postal code you call:

    extractFromAdress(results[0].address_components, "postal_code");
    

    But you could also get other interesting info like:

    extractFromAdress(results[0].address_components, "route");
    extractFromAdress(results[0].address_components, "locality");
    extractFromAdress(results[0].address_components, "country");
    

    etc...

    0 讨论(0)
提交回复
热议问题