Reverse Geocode on Client Side (Google Maps V3 API)

10,844

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.

Share:
10,844
Nyxynyxx
Author by

Nyxynyxx

Updated on June 04, 2022

Comments

  • Nyxynyxx
    Nyxynyxx almost 2 years

    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
      });
    
  • Nyxynyxx
    Nyxynyxx almost 13 years
    Do you know if the reverse geocoding requests contribute to the normal geocoding limits of 2500/day?
  • Khepri
    Khepri almost 13 years
    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.
  • luke_mclachlan
    luke_mclachlan over 9 years
    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#client