Hide
Google Maps JavaScript API v3

Rectangle Zoom

View this example full screen.

JavaScript
// This example creates a rectangle based on the viewport
// on any 'zoom-changed' event.

function initialize() {

  var coachella = new google.maps.LatLng(33.6803003, -116.173894);
  var rectangle;

  var mapOptions = {
    zoom: 11,
    center: coachella,
    mapTypeId: google.maps.MapTypeId.TERRAIN
  };

  var map = new google.maps.Map(document.getElementById('map-canvas'),
      mapOptions);

  rectangle = new google.maps.Rectangle();

  google.maps.event.addListener(map, 'zoom_changed', function() {

    // Get the current bounds, which reflect the bounds before the zoom.
    var rectOptions = {
      strokeColor: '#FF0000',
      strokeOpacity: 0.8,
      strokeWeight: 2,
      fillColor: '#FF0000',
      fillOpacity: 0.35,
      map: map,
      bounds: map.getBounds()
    };
    rectangle.setOptions(rectOptions);
  });
}

google.maps.event.addDomListener(window, 'load', initialize);
JavaScript + HTML
<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Rectangle Zoom</title>
    <style>
      html, body, #map-canvas {
        height: 100%;
        margin: 0px;
        padding: 0px
      }
    </style>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
    <script>
// This example creates a rectangle based on the viewport
// on any 'zoom-changed' event.

function initialize() {

  var coachella = new google.maps.LatLng(33.6803003, -116.173894);
  var rectangle;

  var mapOptions = {
    zoom: 11,
    center: coachella,
    mapTypeId: google.maps.MapTypeId.TERRAIN
  };

  var map = new google.maps.Map(document.getElementById('map-canvas'),
      mapOptions);

  rectangle = new google.maps.Rectangle();

  google.maps.event.addListener(map, 'zoom_changed', function() {

    // Get the current bounds, which reflect the bounds before the zoom.
    var rectOptions = {
      strokeColor: '#FF0000',
      strokeOpacity: 0.8,
      strokeWeight: 2,
      fillColor: '#FF0000',
      fillOpacity: 0.35,
      map: map,
      bounds: map.getBounds()
    };
    rectangle.setOptions(rectOptions);
  });
}

google.maps.event.addDomListener(window, 'load', initialize);

    </script>
  </head>
  <body>
    <div id="map-canvas"></div>
  </body>
</html>