Data Layer: Polygon

by Lawrence Ross

HTML

<!DOCTYPE html>
<html>
  <head>
    <title>Data Layer: Polygon</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
    <script
      src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBIwzALxUPNbatRBj3Xi1Uhp0fFzwWNBkE&callback=initMap&libraries=&v=weekly"
      defer
    ></script>
    <!-- jsFiddle will insert css and js -->
  </head>
  <body>
  <div id="info"></div>
    <div id="map"></div>
  </body>
</html>

CSS

/* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
#map {
  height: 90%;
}

/* Optional: Makes the sample page fill the window. */
html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

JavaScript

// This example uses the Google Maps JavaScript API's Data layer
// to create a rectangular polygon with 2 holes in it.
function initMap() {
  const map = new google.maps.Map(document.getElementById("map"));
  const infowindow = new google.maps.InfoWindow();
  var bounds = new google.maps.LatLngBounds();
  var polygonArray = [];
  map.data.addListener('addfeature', function(e) {
    console.log(e.feature.getGeometry().getArray().length);
    e.feature.getGeometry().getArray().forEach(function(latLngArry){
      console.log(latLngArry.getArray())
      const polygon = new google.maps.Polygon({
        map: map,
        paths: latLngArry.getArray(),
        clickable: false,
        name: e.feature.getProperty("name")
      })
      polygonArray.push(polygon);
    })
    processPoints(e.feature.getGeometry(), bounds.extend, bounds);
    map.fitBounds(bounds);
  });
  const features = map.data.addGeoJson(polygons);
  map.data.setMap(null);
  map.addListener('click', function(event) {
    var content = "";
    for (var i=0;i<polygonArray.length;i++) {
       if (google.maps.geometry.poly.containsLocation(event.latLng, polygonArray[i])) {
          if (content.length!=0) 
            content+=" : "
          content += polygonArray[i].name;
       }
    }
    console.log(content);
    document.getElementById('info').innerHTML = content;
    infowindow.setPosition(event.latLng);
    if (content.length==0) content = "no GeoFence";
    infowindow.setContent(content);
    infowindow.open(map);
  })

  function processPoints(geometry, callback, thisArg) {
    if (geometry instanceof google.maps.LatLng) {
      callback.call(thisArg, geometry);
    } else if (geometry instanceof google.maps.Data.Point) {
      callback.call(thisArg, geometry.get());
    } else {
      geometry.getArray().forEach(function(g) {
        processPoints(g, callback, thisArg);
      });
    }
  }
}
const polygons = {
  "type": "FeatureCollection",
  "features": [{
      "type": "Feature",
     ...