Web Tutorials

Interview Q & A

Code Examples

Utility Tools

Add Geocoding Service on Google Maps

In this example you will learn how to add geocoding service in google map.

Here you can view the output of the example and you can also "try it yourself" by clicking on "Live Demo" button given at the bottom.

Syntax

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);
    }
  });
}

Add Geocoding Service on Google Maps Example

<!DOCTYPE html>  
<html>  
  <head>  <!-- www.techstrikers.com -->
    <title>Add 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: 0px;  
  left: 25%;  
  z-index: 5;  
  background-color: #fff;  
  padding: 0px;  
  border: 1px solid #999;  
  text-align: center;  
  font-family: 'Roboto','sans-serif';  
  line-height: 0px;  
  padding-left: 0px;  
}  
  
    </style>  
        <script src="https://maps.googleapis.com/maps/api/js?signed_in=true&callback=initMap"  
        async defer></script>  
            <script>  
function initMap() {
  var lat_lng = {lat: 22.08672, lng: 79.42444};
  var map = new google.maps.Map(document.getElementById('map'), {  
    zoom: 6,  
    center: lat_lng  
  });  
  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>  
  </head>  
  <body>  
    <div id="floating-panel">  
      <input id="address" type="textbox" value="India, dhuma">  
      <input id="submit" type="button" value="Geocode">  
    </div>  
    <div id="map"></div>  
  </body>  
</html>

Above example will produce following output