为什么Google GeoCoding有时只返回邮政编码?

时间:2012-12-21 16:11:50

标签: jquery google-maps google-maps-api-3 geocoding

如果我通过我的GeoCoding调用只有一个城市和州,它无法返回邮政编码。知道为什么吗?

这是我的电话:

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 个答案:

答案 0 :(得分:1)

如果您确实需要邮政编码,可以将请求退回到反向地理编码器,这应该会为您提供一个代表该城市的邮政编码:

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