使用Google Maps Javascript API V3反向地理编码获取邮政编码

23

我正在尝试在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'];
  }
});
};

当然,这段代码实际上是不起作用的。所以我想知道我需要如何更改它才能从结果数组中提取邮政编码。


看起来我别无选择,只能迭代地址组件并搜索一个带有types[0] == 'postal_code'的地址组件? 有更好的方法吗? - Romaine M.
@RomainM 是的,我会假设除非您想手动从结果中解析它。 - KJYe.Name
是的,您必须遍历数组并查找其types数组中具有“postal_code”的元素,该元素可能位于最后、最前或任何位置。此外,哪个元素?您可能希望从results[0].address_componentsresults本身获取邮政编码:尝试两者并查看在您关心的区域中哪个更好用。一般来说,如果您关心具有完整地址的地点,则建议使用results[0].address_components,如果您关心严格包含您的latlng的邮政编码,则使用results - miguev
23个回答

0
只需在所有类型中搜索 postal_code,找到后返回。

const address_components = [{"long_name": "2b","short_name": "2b","types": ["street_number"]}, { "long_name": "Louis Schuermanstraat","short_name": "Louis Schuermanstraat", "types": ["route"]},{"long_name": "Gent","short_name": "Gent","types": ["locality","political" ]},{"long_name": "Oost-Vlaanderen","short_name": "OV","types": ["administrative_area_level_2","political"]},{"long_name": "Vlaanderen","short_name": "Vlaanderen","types": ["administrative_area_level_1","political"]},{"long_name": "België","short_name": "BE","types": ["country","political"]},{"long_name": "9040","short_name": "9040","types": ["postal_code"]}];
    
// address_components = results[0]address_components

console.log({
  'object': getByGeoType(address_components),
  'short_name': getByGeoType(address_components).short_name,
  'long_name': getByGeoType(address_components).long_name,
  'route': getByGeoType(address_components, ['route']).long_name,
  'place': getByGeoType(address_components, ['locality', 'political']).long_name
});


function getByGeoType(components, type = ['postal_code']) {
  let result = null;
  $.each(components,
    function() {
      if (this.types.some(r => type.indexOf(r) >= 0)) {
        result = this;
        return false;
      }
    });
  return result;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


0

这段简单的代码对我来说有效

for (var i = 0; i < address.length; i++) {
        alert(address[i].types);
        if (address[i].types == "postal_code")
            $('#postalCode').val(address[i].long_name);
        if (address[i].types == "")
            $('#country').val(address[i].short_name);
    }

0

据我所知,zip 是最后一个或倒数第二个。 这就是我的解决方案。

const getZip = function (arr) {
  return (arr[arr.length - 1].types[0] === 'postal_code') ? arr[arr.length - 1].long_name : arr[arr.length - 2].long_name;
};
const zip = getZip(place.address_components);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接