How to convert a location (lat/lng) to address using Reverse Geocoding in Google Geocoding API

Introduction

Here, I will explain how to convert a location (latitude/longitude) to its corresponding address using Reverse Geocoding in Google Geocoding API

Google Maps Reverse Geocoding - Mozilla Firefox_2013-07-10_23-35-03

Description

Reverse Geocoding is the process of converting a geographic location to a human readable address. We can use Google Geocoding API or Google Geocode Service to convert a location to its corresponding address as we did to Geocode an address in the last article.

Reverse Geocoding using Google Geocoding API

In Google Geocoding API, we call API URL to get geocoded data. In the URL we pass response type i.e., JSON or XML with latlng and sensorlatlng is the location that we want to convert and sensor specifies whether our device has sensor in true/false value. Followings are the URLs to return geocoded data of a given location in the JSON and XML format respectively:

JSON format:

http://maps.googleapis.com/maps/api/geocode/json?latlng=-24.448674,135.684569&sensor=false

XML format:

http://maps.googleapis.com/maps/api/geocode/xml?latlng=-24.448674,135.684569&sensor=false

Format of the responses of these URLs can be found here. We can also use “HTTPS” version of these URLs by just replacing “http” with “https”

Reverse Geocoding using Google Geocode Service

var lat = -24.448674;
var lng = 135.684569;
var geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({ 'latLng': latlng }, function(results, status) {
     if (status == google.maps.GeocoderStatus.OK) {
          if (results[1]) {
               var address = results[1].formatted_address;
          } else {
               alert("No results found");
          }
     } else {
          alert("Geocoder failed due to: " + status);
     }
});

In Google Geocode Service, we use JavaScript libraries provided by Google Maps JavaScript API V3 to convert location to address. Here, first we created objects of google.maps.Geocoder and google.maps.LatLng classes then we use geocode() method of the Geocoder class to reverse geocode the location. Here we have set LatLng object to the ‘latLng’ property in the geocode() method to convert given LatLng to an address. Then we extracted formatted_address from the results object in the callback function. formatted_address returns human readable address of a location. Detail of results object and formatted_address can be found here.

Complete HTML of Reverse Geocoding using Google Geocode Service


<!DOCTYPE html>
<html>
<head>
     <title>Google Maps Reverse Geocoding</title>

     <script type="text/javascript"
          src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&sensor=false">
     </script>

     <script type="text/javascript">
          function initialize(lat, lng, address) {
               var mapOptions = {
                    center: new google.maps.LatLng(lat, lng),
                    zoom: 4,
                    mapTypeId: google.maps.MapTypeId.ROADMAP
               };

               var map = new google.maps.Map(document.getElementById("myMap"),
               mapOptions);

               var marker = new google.maps.Marker({
                    position: new google.maps.LatLng(lat, lng),
                    title: address
               });

               marker.setMap(map);
               document.getElementById("txtLatitude").value = lat;
               document.getElementById("txtLongitude").value = lng;
               document.getElementById("txtAddress").value = address;

               var infotext = address + '<hr>' +
                    'Latitude: ' + lat + '<br>Longitude: ' + lng;
               var infowindow = new google.maps.InfoWindow();
               infowindow.setContent(infotext);
               infowindow.setPosition(new google.maps.LatLng(lat, lng));
               infowindow.open(map);
          }

          function getAddress() {
               var lat = parseFloat(document.getElementById("txtLatitude").value);
               var lng = parseFloat(document.getElementById("txtLongitude").value);
               var geocoder = new google.maps.Geocoder();

               var latlng = new google.maps.LatLng(lat, lng);
               geocoder.geocode({ 'latLng': latlng }, function(results, status) {
                    if (status == google.maps.GeocoderStatus.OK) {
                         if (results[1]) {
                              var address = results[1].formatted_address;
                              initialize(lat, lng, address)
                         } else {
                              alert("No results found");
                         }
                    } else {
                         alert("Geocoder failed due to: " + status);
                    }
               });
          }
     </script>

     <style type="text/css">
          .textbox
          {
               border: 1px solid #BABABA;
               color: #212121;
               font-family: "Segoe UI";
               font-size: 100%;
               padding: 4px 8px;
               width: 60%;
               height: 22px;
          }
          .label
          {
               color: #606060;
               float: left;
               font-family: "Segoe UI";
               font-size: 70%;
               padding-bottom: 4px;
               padding-top: 10px;
               text-align: left;
               width: 60%;
          }
          .button
          {
               background-color: rgb(182, 182, 182);
               color: #FFFFFF;
               font-family: "Segoe UI";
               border: 0px none;
               font-size: 100%;
               height: 2.142em;
               min-width: 6em;
               width: 100px;
          }
     </style>
</head>
<body onload="initialize(28.3213, 77.5435, 'New Delhi')">
     <div style="width: 500px;">
          <label for="txtLatitude">
               Latitude</label>
          <div style="clear: both;">
          </div>
          <input id="txtLatitude" type="text" />
          <div style="clear: both;">
          </div>
          <label for="txtLongitude">
               Longitude</label>
          <div style="clear: both;">
          </div>
          <input id="txtLongitude" type="text" />
          <input id="btnAddress" type="button"
               value="Find Address" onclick="getAddress();" />
          <div style="clear: both;">
          </div>
          <label for="txtAddress">
               Address</label>
          <div style="clear: both;">
          </div>
          <input id="txtAddress" type="text" />
          <div id="myMap" style="width: 500px; height: 400px; margin-top: 20px;">
          </div>
     </div>
</body>
</html>

Here, on body onload we call initialize() function with a fixed latitude, longitude and address to show a map with a Marker and an InfoWindow on startup. Then on the Button’s Click event we call getAddress() function that takes latitude, longitude from the two TextBoxes and pass it to the geocode() method as a LatLng object. Then the address returned using reverse geocoding is passed to the initialize() function alongwith latitude and longitude. initialize() function sets address to the txtAddress TextBox and point the map to the given latlng.

Leave a Reply

Your email address will not be published. Required fields are marked *