Web Tutorials

Interview Q & A

Code Examples

Utility Tools

Add Geocoding Component Restriction on Google Maps

In this example you will learn how to add geocoding component restriction on 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, map) {  
  geocoder.geocode({  
    componentRestrictions: {  
      country: 'IN',  
      postalCode: '482001'  
    }  
  }, function(results, status) {  
    if (status === google.maps.GeocoderStatus.OK) {  
      map.setCenter(results[0].geometry.location);  
      new google.maps.Marker({  
        map: map,  
        position: results[0].geometry.location  
      });  
    } else {  
      window.alert('Geocode was not successful for the following reason: ' +  
          status);  
    }  
  });  
 }

Add Geocoding Component Restriction on Google Maps Example

<!DOCTYPE html>  
<html>  
  <head>  
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">  
    <meta charset="utf-8">  
    <title>Add Geocoding Component Restriction</title>  
    <style>  
      html, body {  
        height: 100%;  
        margin: 0;  
        padding: 0;  
      }  
      #map {  
        height: 99%;
        width:99%;
      }  
#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: 5px;  
  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 geocoder = new google.maps.Geocoder;  
  var map = new google.maps.Map(document.getElementById('map'), {  
    zoom: 6,  
    center: lat_lng  
  });  
 document.getElementById('submit').addEventListener('click', function() {  
    geocodeAddress(geocoder, map);  
  });  
}  
  
function geocodeAddress(geocoder, map) {  
  geocoder.geocode({  
    componentRestrictions: {  
      country: 'IN',  
      postalCode: '482001'  
    }  
  }, function(results, status) {  
    if (status === google.maps.GeocoderStatus.OK) {  
      map.setCenter(results[0].geometry.location);  
      new google.maps.Marker({  
        map: map,  
        position: results[0].geometry.location  
      });  
    } else {  
      window.alert('Geocode was not successful for the following reason: ' +  
          status);  
    }  
  });  
}  
  </script>  
  </head>  
  <body>  
    <div id="floating-panel">  
      <pre>componentRestrictions</pre>  
      <button id="submit">Geocode</button>  
    </div>  
    <div id="map"></div>  
  </body>  
</html>

Above example will produce following output