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

标签 google-maps google-maps-api-3 geocoding reverse-geocoding postal-code

每当 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/

相关文章:

android - 在 Android 中保存 map 缩放和位置

google-maps - 在 WebKit 中打印带有多个嵌入式 Google map 的页面会产生图 block 错误

javascript - 在融合表中使用自定义标记以及已对地址进行地理编码的位置

r - 检查 R 中是否存在街道地址

android - 防止在 android 中的谷歌地图上旋转标记

algorithm - 评估谷歌地图中道路 "twistiness"的技术?

javascript - LatLong 落在 D3 + Leaflet 中的给定多边形内

java - Google 地理编码返回 ZERO_RESULTS

java - 我的 AdMob 广告未在 Android Studio 中展示

javascript - Google Maps API map 不显示