Maps API v3 Geocoder componentRestrictions

http://stackoverflow.com/questions/26528744

by upsidown

HTML

<div id="map-canvas"></div>
<button id="codeAddress">
Code address with bounds
</button>
<button id="codeAddressWithCountryRestriction">
Code address with bounds and country component restrictions
</button>

<h4>
  Please use a valid API key in case this one is OVER_QUERY_LIMIT
</h4>
<script src="https://maps.googleapis.com/maps/api/js?v=3.35&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>

CSS

body {
  font-family: Roboto, Arial;
}
#map-canvas {
  height: 400px;
  margin-bottom: 10px;
}

JavaScript

var geocoder, bounds;
var map;

function initialize() {

  map = new google.maps.Map(document.getElementById('map-canvas'), {
    zoom: 5,
    center: new google.maps.LatLng(49, -123)
  });

  geocoder = new google.maps.Geocoder();

  bounds = new google.maps.LatLngBounds(
    new google.maps.LatLng(46.7827, -125.6207),
    new google.maps.LatLng(51.7827, -120.620)
  );

  // Create rectangle to show the bounds
  var rectangle = new google.maps.Rectangle({
    bounds: bounds,
    fillColor: 'white',
    fillOpacity: .5,
    map: map
  });

  // Bind click event listener for buttons
  document.getElementById("codeAddress").addEventListener('click', codeAddress, false);
  document.getElementById("codeAddressWithCountryRestriction").addEventListener('click', codeAddressWithCountryRestriction, false);
}

function codeAddress() {

  var address = '35 Bastion st.';

  geocoder.geocode({
    'address': address,
    'bounds': bounds
  }, function(results, status) {

    if (status == google.maps.GeocoderStatus.OK) {

      console.log(results);

      map.setCenter(results[0].geometry.location);

      var marker = new google.maps.Marker({
        map: map,
        position: results[0].geometry.location
      });

    } else {

      alert("Geocode was not successful for the following reason: " + status);
    }
  });
}

function codeAddressWithCountryRestriction() {

  var address = '35 Bastion st.';

  geocoder.geocode({
    'address': address,
    'bounds': bounds,
    'componentRestrictions': {
      'country': 'CA'
    }
  }, function(results, status) {

    if (status == google.maps.GeocoderStatus.OK) {

      console.log(results);

      map.setCenter(results[0].geometry.location);

      var marker = new google.maps.Marker({
        map: map,
        position: results[0].geometry.location
      });

    } else {

      alert("Geocode was not successful for the following reason: " + status);
    }
  });
}

document.body.onload = initialize();