使用Google Maps Javascript API V3反向地理编码检索邮政编码

Rom*_* M. 18 google-maps geocoding postal-code reverse-geocoding google-maps-api-3

每当googlemaps视口中心发生变化时,我都会尝试使用邮政编码向我的数据库提交查询.我知道这可以通过反向地理编码完成,例如:

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'];
  }
});
};
Run Code Online (Sandbox Code Playgroud)

当然,这段代码实际上并不起作用.所以我想知道如何更改这个以便从结果数组中提取邮政编码.谢谢

Tuc*_*uco 19

到目前为止我所意识到的是,在大多数情况下,ZIPCODE 始终是每个返回地址中的最后一个值,因此,如果您想要检索第一个zipcode(这是我的情况),您可以使用以下方法:

var address = results[0].address_components;
var zipcode = address[address.length - 1].long_name;
Run Code Online (Sandbox Code Playgroud)

  • 自从我发表这个答案以来已经很长时间了,但我记得在另一个项目中我发现索引会因结果而异.换句话说,邮政编码有时可能不是最后一项. (2认同)
  • @Tuco,索引确实发生了变化。有时它是最后一个元素,其他则是倒数第二个。虽然不确定这是什么原因。 (2认同)
  • 对于那些想知道为什么邮政编码有时位于倒数第二位的人来说,这是因为在某些情况下最后一项是`postal_code_suffix`键 (2认同)

EMu*_*tes 11

使用JQuery?

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

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

short_name或long_name将
在"searchPostalCode" 上方工作,var将包含邮政(zip?)代码IF,并且仅在您从Google Maps API获取时才会包含.

有时你不会得到"postal_code"来回报你的查询.


Jef*_*f S 11

您可以使用underscore.js libraray轻松完成此操作:http://documentcloud.github.com/underscore/#find

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


Rom*_* M. 10

好吧,所以我明白了.解决方案比我想要的更加丑陋,我可能不需要最后一个for循环,但这里是需要从address_components []中提取废话的其他人的代码.这是在地理编码器回调函数中

for(i; 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;
                    }
                }
            }
    }
Run Code Online (Sandbox Code Playgroud)

  • 嘿@SamCromer 我测试了上面的代码,答案也未定义。也许您还忘记在 for 循环之前放置 var i= 0 。我加了,效果很好! (2认同)
  • 这很有效,只要您将 'for(i; i &lt; results.length; i++){' 更改为 'for(i=0; i &lt; results.length; i++){'。非常感谢这个解决方案。 (2认同)