如何反转地理编码坐标以使用Google Map获取邮政密码? [关闭]

问题描述 投票:5回答:1

我正在制作一个应用程序,它将获取用户的当前位置或他的自定义地图标记以找出纬度和经度,然后使用这些值,我想知道该区域的密码(邮政编码),以便我可以告诉用户商品是否可以是否在该地区交付。

我已经尝试过了:http://www.geonames.org/export/ws-overview.html,但是它没有完整的数据,并且所拥有的也不是很准确。还有其他我可以用来获取此类数据的API吗?

javascript api google-maps geocoding
1个回答
15
投票
[如果您有位置(和Google Maps API v3地图),请reverse geocode该位置。处理返回的邮政编码代码记录(请参见this SO post for an example)。

// assumes comma separated coordinates in a input element function codeLatLng() { var input = document.getElementById('latlng').value; var latlngStr = input.split(',', 2); var lat = parseFloat(latlngStr[0]); var lng = parseFloat(latlngStr[1]); var latlng = new google.maps.LatLng(lat, lng); geocoder.geocode({'latLng': latlng}, processRevGeocode); } // process the results function processRevGeocode(results, status) { if (status == google.maps.GeocoderStatus.OK) { var result; if (results.length > 1) result = results[1]; else result = results[0]; if (result.geometry.viewport) map.fitBounds(result.geometry.viewport); else if (result.geometry.bounds) map.fitBounds(result.geometry.bounds); else { map.setCenter(result.geometry.location); map.setZoom(11); } if (marker && marker.setMap) marker.setMap(null); marker = new google.maps.Marker({ position: result.geometry.location, map: map }); infowindow.setContent(results[1].formatted_address); infowindow.open(map, marker); displayPostcode(results[0].address_components); } else { alert('Geocoder failed due to: ' + status); } } // displays the resulting post code in a div function displayPostcode(address) { for (p = address.length-1; p >= 0; p--) { if (address[p].types.indexOf("postal_code") != -1) { document.getElementById('postcode').innerHTML= address[p].long_name; } } }

Working example (displays a postcode from a geocoded address, reverse geocoded coordinates, or a click on the map)
© www.soinside.com 2019 - 2024. All rights reserved.