客户端的反向地理编码(Google Maps V3 API)

时间:2011-07-02 17:56:31

标签: javascript google-maps geocoding reverse-geocoding

如何使用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
  });

1 个答案:

答案 0 :(得分: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);
  }
});

Example directly from Google

希望有所帮助。