How to find latitude/longitude of an address using Google Geocoding API

Introduction

Here, I will explain how to find latitude and longitude of a given address using Google Geocoding API and Google Geocoding Service

Google Maps - Mozilla Firefox_2013-07-01_08-02-26

Description

Geocoding is the process of converting an address into latitude and longitude. We can use Google Geocoding API to convert an address to its latitude/longitude by making HTTP request. Google Geocode Service in Google Maps JavaScript API V3 provides classes that we can use to get latitude and longitude of an address.

Google Geocoding API

In Google Geocoding API, we call an URL with some parameters to return geocoded data. Geocoded data returned by this API can be in the form of XML or JSON. Followings are the URLs to return geocoded data of a given address in XML and JSON format:

JSON format:
http://maps.googleapis.com/maps/api/geocode/json?address=Eden+Garden+,Kolkata&sensor=false

XML format:
http://maps.googleapis.com/maps/api/geocode/xml?address=Eden+Garden+,Kolkata&sensor=false

Here, ‘address’ specifies the address to geocode and ‘sensor’ specifies whether your device has a location sensor with true/false value. Geocoding responses of these URLs can be found here.

Google Geocode Service

In Google Geocode Service, we use geocode method of the google.maps.Geocoder class to geocode an address. geocode method takes address and a callback function as parameters. Callback function provides results array and status code, results array contains latitude/longitude, address, and other geographical data. And status code contains GeocoderStatus which can be used to track errors in geocoding. We can use following code to get latitude and longitude of an address:

var address = "Eden Gardens, Kolkata";
var geocoder = new google.maps.Geocoder();

geocoder.geocode({ 'address': address }, function(results, status) {
     if (status == google.maps.GeocoderStatus.OK) {
          var latitude = results[0].geometry.location.lat();
          var longitude = results[0].geometry.location.lng();
          txtLatitude.value = latitude;
          txtLongitude.value = longitude;
     }
     else {
          alert('Geocode error: ' + status);
     }
});

Complete HTML for Google Geocode Service


<!DOCTYPE html>
<html>
<head id="Head1" runat="server">
     <title>Google Maps 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);

               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 getLatLng() {
               var address = document.getElementById("txtAddress").value;
               var geocoder = new google.maps.Geocoder();
               geocoder.geocode({ 'address': address }, function(results, status) {
                    if (status == google.maps.GeocoderStatus.OK) {
                         var longaddress = results[0].address_components[0].long_name;
                         var latitude = results[0].geometry.location.lat();
                         var longitude = results[0].geometry.location.lng();
                         txtLatitude.value = latitude;
                         txtLongitude.value = longitude;
                         initialize(results[0].geometry.location.lat(), results[0].geometry.location.lng(), longaddress);
                    } else {
                         alert('Geocode error: ' + status);
                    }
               });
          }
     </script>

     <style type="text/css">
          .textbox
          {
               border: 1px solid #BABABA;
               color: #212121;
               font-family: "Segoe UI";
               font-size: 100%;
               padding: 4px 8px;
               width:325px;
               height:22px;
          }

          .label
          {
               color: #606060;
               float: left;
               font-family: "Segoe UI";
               font-size: 70%;
               padding-bottom: 4px;
               padding-top: 10px;
               text-align: left;
               width:150px;
          }

          .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="txtAddress" class="label">Address</label>
          <div style="clear:both;"></div>
          <input id="txtAddress" type="text" class="textbox" />
          <input id="btnGetLatLng" type="button" class="button" value="Find" onclick="getLatLng();"/>
          <div style="clear:both;"></div>
          <label for="txtLatitude" class="label">Latitude</label>
          <div style="clear:both;"></div>
          <input id="txtLatitude" type="text" class="textbox" />
          <div style="clear:both;"></div>
          <label for="txtLongitude" class="label">Longitude</label>
          <div style="clear:both;"></div>
          <input id="txtLongitude" type="text" class="textbox" />
     </div>

     <div id="myMap" style="width: 500px; height: 400px; margin-top:20px;">
     </div>
</body>
</html>

Here, we call getLatLng() function on Button’s click. In getLatLng() function, we get address from the TextBox and call geocode method of the Geocoder class. Then we extracted latitude, longitude and address’s long_name from the result array and put latitude and longitude in TextBoxes. Then we call initialize function with latitude, longitude and address to show the map with Marker and InfoWindow.

3 thoughts on “How to find latitude/longitude of an address using Google Geocoding API

Leave a Reply

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