Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
  });
like image 268
Nyxynyxx Avatar asked Jul 02 '11 17:07

Nyxynyxx


People also ask

Is Google reverse geocoding API free?

The Geocoding API uses a pay-as-you-go pricing model.


1 Answers

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.

like image 116
Khepri Avatar answered Nov 14 '22 23:11

Khepri