Google Maps with rectangle

Demonstrates how to rotate rectangle in Google Maps

by Vadim Gremyachev

HTML

<div id="floating-panel"><input type="button" id="btnRotate" value="Auto Rotate"></div>
 <div id="map"></div>
 <script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap"></script>

CSS

html, body {
    height: 100%;
    margin: 0;
    padding: 0;
}

#map {
    height: 100%;
}

#floating-panel {
  position: absolute;
  top: 10px;
  left: 25%;
  z-index: 5;
  background-color: #fff;
  padding: 5px;
  border: 1px solid #999;
  text-align: center;
  font-family: 'Roboto','sans-serif';
  line-height: 30px;
  padding-left: 10px;
}

JavaScript

function initMap() {
    var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 13,
        center: { lat: 33.678, lng: -116.243 },
        mapTypeId: google.maps.MapTypeId.TERRAIN
    });

    var rectangle = new google.maps.Rectangle({
        strokeColor: '#FF0000',
        strokeOpacity: 0.8,
        strokeWeight: 2,
        fillColor: '#FF0000',
        fillOpacity: 0.35,
        map: map,
        bounds: {
            north: 33.685,
            south: 33.671,
            east: -116.224,
            west: -116.251
        }
    });

    var rectPoly = createPolygonFromRectangle(rectangle); //create a polygom from a rectangle

    rectPoly.addListener('click', function(e) {
        rotatePolygon(rectPoly,10);
    });


    document.getElementById('btnRotate').onclick = function() {
        window.setInterval(function() {
            rotatePolygon(rectPoly, 10);
        }, 500);
    };
}



function createPolygonFromRectangle(rectangle) {
    var map = rectangle.getMap();
  
    var coords = [
      { lat: rectangle.getBounds().getNorthEast().lat(), lng: rectangle.getBounds().getNorthEast().lng() },
      { lat: rectangle.getBounds().getNorthEast().lat(), lng: rectangle.getBounds().getSouthWest().lng() },
      { lat: rectangle.getBounds().getSouthWest().lat(), lng: rectangle.getBounds().getSouthWest().lng() },
      { lat: rectangle.getBounds().getSouthWest().lat(), lng: rectangle.getBounds().getNorthEast().lng() }
    ];

    // Construct the polygon.
    var rectPoly = new google.maps.Polygon({
        path: coords
    });
    var properties = ["strokeColor","strokeOpacity","strokeWeight","fillOpacity","fillColor"];
    //inherit rectangle properties 
    var options = {};
    properties.forEach(function(property) {
        if (rectangle.hasOwnProperty(property)) {
            options[property] = rectangle[property];
        }
    });
    rectPoly.setOptions(options);

    rectangle.setMap(null);
    rectPoly.setMap(map);
    return...