Why does Google GeoCoding only sometimes return the postal code?

杀马特。学长 韩版系。学妹 提交于 2019-12-10 17:46:21

问题


If I pass my GeoCoding call only a city and state it fails to return the postal code. Any idea why?

Here is my call:

var test = 'New York, NY';

var geocoder = new google.maps.Geocoder();         
geocoder.geocode({ 'address': test }, function (results, status) {          

if (status == google.maps.GeocoderStatus.OK) {  

    var lat = results[0].geometry.location.lat();
    var lng = results[0].geometry.location.lng();

    var result=results[0].address_components;

    //console.log(result);

    var postal = null;
    var city = null;
    var state = null;
    var country = null;

    for(var i=0;i<result.length;++i){
        if(result[i].types[0]=="postal_code"){
            postal = result[i].long_name;
        }
        if(result[i].types[0]=="administrative_area_level_1"){
            state = result[i].long_name;
        }
        if(result[i].types[0]=="locality"){
            city = result[i].long_name;
        }
        if(result[i].types[0]=="country"){
            country = result[i].long_name;
        }
    }

    alert("POSTAL: " + postal);
    alert("STATE: " + state);
    alert("CITY: " + city);
    alert("COUNTRY: " + country);

}

回答1:


If you really need a zip code, you can throw the request back to the reverse geocoder, that should give you a zip code somewhat representative of the city:

if (!postal) {
  geocoder.geocode({ 'location': results[0].geometry.location }, function (results, status) {          
    if (status == google.maps.GeocoderStatus.OK) {  

      var result=results[0].address_components;

      for(var i=0;i<result.length;++i){
       if(result[i].types[0]=="postal_code"){
          postal = result[i].long_name;
       }
      }
      alert("POSTAL: " + postal);
    }
});
} else alert("POSTAL: " + postal);

example



来源:https://stackoverflow.com/questions/13993474/why-does-google-geocoding-only-sometimes-return-the-postal-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!