2012-12-21 48 views
3

如果我只通过我的GeoCoding呼叫某个城市并声明无法返回邮政编码。任何想法为什么?为什么Google 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

[对官方USPS文件的快速查询](http://smartystreets.com/?city=new+york&state=ny)显示纽约州,纽约州匹配149个邮政编码。像凯文说,你期望哪一个,没有更具体的信息,像一个实际的地址? – Matt

+0

一个城市也有很多经纬度的组合,它决定一个返回。为什么不返回它返回的经纬度的拉链? – Danial

回答

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

相关问题