每当 googlemaps 视口(viewport)中心发生变化时,我都会尝试使用邮政编码向我的数据库提交查询。我知道这可以通过反向地理编码来完成,例如:
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'];
}
});
};
当然,这段代码实际上不起作用。所以我想知道我需要如何更改它才能从结果数组中提取邮政编码。
谢谢
最佳答案
您也可以使用 JavaScript .find
类似于下划线 _.find
的方法方法,但它是 native 的,不需要额外的依赖。
const zip_code = results[0].address_components.find(addr => addr.types[0] === "postal_code").short_name;
关于google-maps - 使用 Google Maps Javascript API V3 反向地理编码检索邮政编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5341023/