Reverse Geocode on Client Side (Google Maps V3 API)
Asked Answered
G

1

5

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
  });
Gratulate answered 2/7, 2011 at 17:56 Comment(0)
D
13

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.

Dukedom answered 2/7, 2011 at 19:4 Comment(3)
Do you know if the reverse geocoding requests contribute to the normal geocoding limits of 2500/day?Gratulate
I'm almost certain it does. It's the same method call with a just a different param. Just make sure you're doing the geocoding from the client and you should be just fine.Dukedom
sorry to comment so late but I'm pretty sure that if geocoding is done client side, then the quota isn't 2500 requests/day. check here: developers.google.com/maps/articles/geocodestrat#clientUpswing

© 2022 - 2024 — McMap. All rights reserved.