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

Reverse Geocode on Client Side (Google Maps V3 API)

本文关键字:Maps Google V3 API 代码 客户端      更新时间:2023-09-26

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

过程完全相同,只是提供了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 的示例

希望能有所帮助。