简体   繁体   中英

Reverse Geocode on Client Side (Google Maps V3 API)

How do you do a Reverse Geocode on the clientside using Google Maps V3 API? The forward geocode from address to LatLng is straight forward (code below), but how do you do the same for reverse geocode?

Normal Geocode Code:

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
  });

The process is exactly the same, with the minor difference that instead of supplying an address object to the geocode function you supply a LatLng object

Reverse Geocode Code:

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

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM