Drawing Polygons On Google Map

Introduction

A polygon is a two-dimensional closed figure formed with straight lines. Triangles, quadrilaterals, hexagons, and pentagons are different examples of polygons. We can draw these on Google Maps using new.google.maps.Polygon constructor class. Coordinates are in sequence to draw a polygon. We can define custom colors, stroke, fill, stroke widths of the edges, opacities, color for the enclosed area. The most important thing to be noticed here is we can define colors in hexadecimal format only. Other formats are not supported.

Adding A Polygon

We can add a polygon by defining path property as an array of objects of type MVCArray. For drawing a polygon we need to pass sequence latLng coordinates. The Map API will convert this MVCArray into an array of arrays when constructing polygon on the Map. Let us see an example of how to add a polygon on Google Maps:





<!DOCTYPE html>
<html>

<head>
  <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
  <meta charset="utf-8">
  <title>Google Map</title>
  <style>
    #Gmap {
      height: 600px;
      width: 100%;
    }

    html,
    body {
      height: 100%;
      margin: 0;
      padding: 0;
    }
  </style>
</head>

<body>
  <div id="Gmap"></div>
  <script>
    function initMap() {
      var mapOptions = {
        streetViewControl: false,
        center: { lat: 21.291, lng: -157.821 },
        zoom: 2,
        mapTypeId: google.maps.MapTypeId.HYBRID,
      };
      var map = new google.maps.Map(document.getElementById('Gmap'), mapOptions);
      var flightPlanCoordinates = [
        { lat: 38, lng: -100 },
        { lat: 21, lng: -120 },
        { lat: -18, lng: -100 },
      ];
      var flightPath = new google.maps.Polygon({
        path: flightPlanCoordinates,
        geodesic: false,
        strokeColor: '#FFC0CB',
        strokeOpacity: 0.75,
        strokeWeight: 1
      });

      flightPath.setMap(map);
    }
  </script>
  <script
    src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js"></script>
  <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDShdMS18_xwv3VHpzQlGgr10v0SmD7SyE&callback=initMap">
    </script>
</body>

</html>

In the above example, we will see LatLng coordinates are defined by flightPlanCoordinates array. We have defined three sets of coordinates here, the Map API will automatically connect the last coordinate to the first one to draw a polygon. We can even define the first coordinate as the last coordinate in our array. 

Setting Fill Color: Set the fillColor property of the Polygon constructor.


      var flightPath = new google.maps.Polygon({
        path: flightPlanCoordinates,
        strokeColor: '#FFCCB',
        strokeOpacity: 0.75,
        strokeWeight: 1,
        fillColor: '#00ff00'
      });

      flightPath.setMap(map);

The options which are defined as PolygonOptions are as follows:

  • strokeColor: We can specify this option as a hexadecimal color value. Color names are not permitted in this. It is a stroke color.
  • strokeOpacity: define opacity for stroke or line. Specify a value between 0.0 and 1.1.
  • strokeWeight: define a width for the stroke in pixels.
  • fillOpacity: define opacity for the fill color. Specify a value between 0.0 and 1.1.

Setting It On The Map

We will call the setMap() method on the Polygon object and pass the map reference as follows:

 flightPath.setMap(map);

Polygon Methods

Now we will see how to inspect and manipulate MVCArray associated with the polygon. A polygon is drawn by taking different LatLng coordinates as input in the path property. We can use the getPath() method to get that MVCArray array. Following methods can be used with this array:

  • getAt() - returns the latLng at given index(zero-based).
  • insertAt() - inserts the passed latLng at that index. Existing one will be moved forward.
  • removeAt() - removes a latLng at that index.
Now we will see an example where on clicking on the polygon we will show all the coordinates in an infoWindow. The code is as follows:




<!DOCTYPE html>
<html>

<head>
  <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
  <meta charset="utf-8">
  <title>Google Map</title>
  <style>
    #Gmap {
      height: 600px;
      width: 100%;
    }

    html,
    body {
      height: 100%;
      margin: 0;
      padding: 0;
    }
  </style>
</head>

<body>
  <div id="Gmap"></div>
  <script>
    var map;
    var infoWindow;
    function initMap() {
      var mapOptions = {
        streetViewControl: false,
        center: { lat: 21.291, lng: -157.821 },
        zoom: 2,
        mapTypeId: google.maps.MapTypeId.HYBRID,
      };
      map = new google.maps.Map(document.getElementById('Gmap'), mapOptions);
      var flightPlanCoordinates = [
        { lat: 38, lng: -100 },
        { lat: 21, lng: -120 },
        { lat: -18, lng: -100 },
      ];
      var flightPath = new google.maps.Polygon({
        path: flightPlanCoordinates,
        geodesic: false,
        strokeColor: '#FFCCB',
        strokeOpacity: 0.75,
        strokeWeight: 1,
        fillColor: '#00ff00'
      });

      flightPath.setMap(map);
      flightPath.addListener('click', polygonClick);
      infoWindow = new google.maps.InfoWindow;
    }
  
    function polygonClick(event) {
      var pathVertices = this.getPath();
      var windowText = '<b>Polygon</b><br>';
      for (var i = 0; i < pathVertices.getLength(); i++) {
        var pos = pathVertices.getAt(i);
        windowText += '<br>' + 'Coordinate ' + i + ':<br>' + pos.lat() + ',' +
          pos.lng();
      }
      infoWindow.setContent(windowText);
      infoWindow.setPosition(event.latLng);
      infoWindow.open(map);
    }


  </script>
  <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDShdMS18_xwv3VHpzQlGgr10v0SmD7SyE&callback=initMap">
    </script>
</body>
</html>

We have used the getPath() method to get the MVCArray. Then we used getAt() method to get the latLng coordinates.

Comments