Google Maps API - SPLessons

Chapter 13

Google Maps Geocoding API

Google Maps Geocoding API

The chapter below demonstrates about the Google Maps Geocoding API and following are the concepts covered.

  • Overview on Geocoding API
  • Reverse Geocoding

Overview on Geocoding API

The process of converting human-readable address into Geographical co-ordinates is known as the Geocoding.

The Google Maps API provide access for Geocoding service by calling an external server. A geocoder class is used for geocoding the user input dynamically. A call back method is used to execute the user request and process the result(s).

Google Maps provide the user an initial quota for requesting Geocoding to load the API and additional requests are allowed in terms of rate-limit on per-second base if the quota usage limit exceed.

Using the object google.maps.Geocoder user can access the Geocoding service of Google Maps API and the method Geocoder.geocode() is used to request the geocoding service and pass the GeocoderRequest object which contains the following parameters.

The example below demonstrate the simple code for geocoding the address and place a mark depending on the given LatLng co-ordinates.

<!DOCTYPE html>
<html>
  <head>
    <title>Google Maps Geocoding service</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <style>
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
      #map {
        height: 100%;
      }
#floating-panel {
  position: absolute;
  top: 10px;
  left: 40%;
  z-index: 5;
  background-color: #fff;
  padding: 5px;
  border: 1px solid #999;
  text-align: center;
  font-family: 'Roboto','sans-serif';
  line-height: 30px;
  padding-left: 10px;
}
    </style>
  </head>
  <body>
    <div id="floating-panel">
      <input id="address" type="textbox" value="India, HYD">
      <input id="submit" type="button" value="Geocode">
    </div>
    <div id="map"></div>
    <script>
function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 10,
    center: {lat: 17.3700, lng: 78.4800}
  });
  var geocoder = new google.maps.Geocoder();

  document.getElementById('submit').addEventListener('click', function() {
    geocodeAddress(geocoder, map);
  });
}
function geocodeAddress(geocoder, resultsMap) {
  var address = document.getElementById('address').value;
  geocoder.geocode({'address': address}, function(results, status) {
    if (status === google.maps.GeocoderStatus.OK) {
      resultsMap.setCenter(results[0].geometry.location);
      var marker = new google.maps.Marker({
        map: resultsMap,
        position: results[0].geometry.location
      });
    } else {
      alert('Geocode was not successful for the following reason: ' + status);
    }
  });
}
    </script>
    <script src="https://maps.googleapis.com/maps/api/js?key=&signed_in=true&callback=initMap"
        async defer></script>
  </body>
</html>

Reverse Geocoding

The Reverse Geocoding is quite opposite to general Geocoding i.e., the process of converting the human-readable address into location is known as Geocoding whereas the process of converting location into human-readable address is known as Reverse Geocoding.

Reverse Geocoding directly supported by the Geocoder by separating the LatLng co-ordinates with commas in location parameters without giving a textual address. The address for the give place can be find using the placeID.

Using Reverse Geocoding will not trace the exact address but gives the closest address location.

The example below demonstrate the code for Reverse Geocoding by Location, here in the code depending on LatLng co-ordinate values the map gets centered and display the info window providing the address for that particular location.

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Reverse Geocoding by location</title>
    <style>
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
      #map {
        height: 100%;
      }
#floating-panel {
  position: absolute;
  top: 10px;
  left: 25%;
  z-index: 5;
  background-color: #fff;
  padding: 5px;
  border: 1px solid #999;
  text-align: center;
  font-family: 'Roboto','sans-serif';
  line-height: 30px;
  padding-left: 10px;
}
    </style>
    <style>
      #floating-panel {
        position: absolute;
        top: 5px;
        left: 50%;
        margin-left: -180px;
        width: 350px;
        z-index: 5;
        background-color: #fff;
        padding: 5px;
        border: 1px solid #999;
      }
      #latlng {
        width: 225px;
      }
    </style>
  </head>
  <body>
    <div id="floating-panel">
      <input id="latlng" type="text" value="17.2400,78.4281">
      <input id="submit" type="button" value="Reverse Geocode">
    </div>
    <div id="map"></div>
    <script>
function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 7,
    center: {lat: 17.3700, lng: 78.4800}
  });
  var geocoder = new google.maps.Geocoder;
  var infowindow = new google.maps.InfoWindow;

  document.getElementById('submit').addEventListener('click', function() {
    geocodeLatLng(geocoder, map, infowindow);
  });
}
function geocodeLatLng(geocoder, map, infowindow) {
  var input = document.getElementById('latlng').value;
  var latlngStr = input.split(',', 2);
  var latlng = {lat: parseFloat(latlngStr[0]), lng: parseFloat(latlngStr[1])};
  geocoder.geocode({'location': latlng}, function(results, status) {
    if (status === google.maps.GeocoderStatus.OK) {
      if (results[1]) {
        map.setZoom(11);
        var marker = new google.maps.Marker({
          position: latlng,
          map: map
        });
        infowindow.setContent(results[1].formatted_address);
        infowindow.open(map, marker);
      } else {
        window.alert('No results found');
      }
    } else {
      window.alert('Geocoder failed due to: ' + status);
    }
  });
}
    </script>
    <script src="https://maps.googleapis.com/maps/api/js?key=&signed_in=true&callback=initMap"
        async defer></script>
  </body>
</html>

Place IDs

The Google Maps API uses some textual identifiers to identify or locate a place on the map which is known as place IDs

Google Maps provide place IDs for different locations like parks, landmarks, businesses places etc. this IDs are maintained stable and can be reused as per the need.

The code below demonstrate the Google Maps API Place IDs identifier.

<!DOCTYPE html>
<html>
  <head>
    <title>PlaceID finder</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <style>
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
      #map {
        height: 100%;
      }
      .controls {
        background-color: #fff;
        border-radius: 2px;
        border: 1px solid transparent;
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
        box-sizing: border-box;
        font-family: Roboto;
        font-size: 15px;
        font-weight: 300;
        height: 29px;
        margin-left: 17px;
        margin-top: 10px;
        outline: none;
        padding: 0 11px 0 13px;
        text-overflow: ellipsis;
        width: 400px;
      }
      .controls:focus {
        border-color: #4d90fe;
      }
    </style>
  </head>
  <body>
    <input id="pac-input" class="controls" type="text"
        placeholder="Enter a location">
    <div id="map"></div>
    <script>
function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    center: {lat: 17.3700, lng: 78.4800},
    zoom: 10
  });
  var input = document.getElementById('pac-input');
  var autocomplete = new google.maps.places.Autocomplete(input);
  autocomplete.bindTo('bounds', map);
  map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
  var infowindow = new google.maps.InfoWindow();
  var marker = new google.maps.Marker({
    map: map
  });
  marker.addListener('click', function() {
    infowindow.open(map, marker);
  });
  autocomplete.addListener('place_changed', function() {
    infowindow.close();
    var place = autocomplete.getPlace();
    if (!place.geometry) {
      return;
    }
    if (place.geometry.viewport) {
      map.fitBounds(place.geometry.viewport);
    } else {
      map.setCenter(place.geometry.location);
      map.setZoom(17);
    }

    // Set the position of the marker using the place ID and location.
    marker.setPlace({
      placeId: place.place_id,
      location: place.geometry.location
    });
    marker.setVisible(true);

    infowindow.setContent('<div><strong>' + place.name + '</strong><br>' +
        'Place ID: ' + place.place_id + '<br>' +
        place.formatted_address);
    infowindow.open(map, marker);
  });
}
    </script>
    <script src="https://maps.googleapis.com/maps/api/js?key=&libraries=places&signed_in=true&callback=initMap"
        async defer></script>
  </body>
</html>

The example below demonstrate the code for Reverse Geocoding by using the Place IDs, here in the code depending on place ID the map gets centered and display the info window providing the address for that particular location.

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Reverse Geocoding by Place ID</title>
    <style>
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
      #map {
        height: 100%;
      }
#floating-panel {
  position: absolute;
  top: 10px;
  left: 40%;
  z-index: 5;
  background-color: #fff;
  padding: 5px;
  border: 1px solid #999;
  text-align: center;
  font-family: 'Roboto','sans-serif';
  line-height: 30px;
  padding-left: 10px;
}
    </style>
    <style>
      #floating-panel {
        width: 440px;
      }
      #place-id {
        width: 250px;
      }
    </style>
  </head>
  <body>
    <div id="floating-panel">
      <!-- Supply a default place ID for a place in Brooklyn, New York. -->
      <input id="place-id" type="text" value="ChIJa5sujFWXyzsRnU6EzGNTcCU">
      <input id="submit" type="button" value="Reverse Geocode by Place ID">
    </div>
    <div id="map"></div>
    <script>
// Initialize the map.
function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 10,
    center: {lat: 17.3700, lng: 78.4800}
  });
  var geocoder = new google.maps.Geocoder;
  var infowindow = new google.maps.InfoWindow;

  document.getElementById('submit').addEventListener('click', function() {
    geocodePlaceId(geocoder, map, infowindow);
  });
}
// This function is called when the user clicks the UI button requesting
// a reverse geocode.
function geocodePlaceId(geocoder, map, infowindow) {
  var placeId = document.getElementById('place-id').value;
  geocoder.geocode({'placeId': placeId}, function(results, status) {
    if (status === google.maps.GeocoderStatus.OK) {
      if (results[0]) {
        map.setZoom(12);
        map.setCenter(results[0].geometry.location);
        var marker = new google.maps.Marker({
          map: map,
          position: results[0].geometry.location
        });
        infowindow.setContent(results[0].formatted_address);
        infowindow.open(map, marker);
      } else {
        window.alert('No results found');
      }
    } else {
      window.alert('Geocoder failed due to: ' + status);
    }
  });
}
    </script>
    <script src="https://maps.googleapis.com/maps/api/js?key=&signed_in=true&callback=initMap"
        async defer></script>
  </body>
</html>

Summary

  • Geocoding service need a call back method for executing the user request and this call back method should pass the two important parameters for holding result and status.
  • The Geocoder return more than one result.
  • The Reverse Geocoding cannot trace the exact address but can give the nearest place or location.

  • Copy the API key obtained from Google Maps API and paste using the JavaScript tag in the code for loading Maps.
  • Set the required Map Properties for better output.
  • Make sure the latitude and longitudes of the required location mentioned to be correct.
  • Do not add the API key in the code exposed to public.
  • Make sure the correct place IDs for preferred locations before running the application.