5

您如何使用 Google Maps V3 API 在客户端执行反向地理编码?从地址到 LatLng 的正向地理编码是直截了当的(代码如下),但你如何为反向地理编码做同样的事情?

普通地理编码:

geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
  if (status == google.maps.GeocoderStatus.OK) {
    map.setCenter(results[0].geometry.location);
    var marker = new google.maps.Marker({
    map: map,
    position: results[0].geometry.location
  });
4

1 回答 1

13

该过程完全相同,只是没有向地理编码函数提供地址对象,而是提供了一个 LatLng 对象

反向地理编码:

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}, function(results, status) {
  if (status == google.maps.GeocoderStatus.OK) {
    if (results[1]) {
      map.setZoom(11);
      marker = new google.maps.Marker({
          position: latlng, 
          map: map
      }); 
      infowindow.setContent(results[1].formatted_address);
      infowindow.open(map, marker);
    } else {
      alert("No results found");
    }
  } else {
    alert("Geocoder failed due to: " + status);
  }
});

直接来自 Google 的示例

希望有帮助。

于 2011-07-02T19:04:41.977 回答