Google Maps example

Demonstrates how to determine whether the polygon is located inside a map viewport or not

by Christian Bonato

HTML

<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%;
}

JavaScript

var g_polygongs = [];
function initMap() {
    var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 3,
        center: { lat: 24.886, lng: -70.268 },
        mapTypeId: google.maps.MapTypeId.TERRAIN
    });

    //generate polygons
    for (var i = 0; i < 200; i++) {
        var startLng = getRandomArbitrary(-90.0, 0.0);
        var startLat = getRandomArbitrary(0.0, 60.0);
        var coords = [
            { lat: startLat, lng: startLng },
            { lat: startLat - 6.0, lng: startLng + 4.0 },
            { lat: startLat + 6.0, lng: startLng + 8.0 },
            { lat: startLat, lng: startLng }
        ];
        g_polygongs.push(createPolygon(map,coords));
    }


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

      g_polygongs.forEach(function(p) {
          if (containsPolygon(map, p)) {
              p.setOptions({ strokeWeight: 2.0, fillColor: 'green' });
          } else {
              p.setOptions({ fillColor: 'orange' });
          }

      });
    });

}


function containsPolygon(map,polygon) {
    return polygon.getPaths().getArray().every(function (path) {
        return path.getArray().every(function(coord) {
            return map.getBounds().contains(coord);
        });
    });
}





function createPolygon(map,coords) {
    // Construct the polygon.
    var poly = new google.maps.Polygon({
        paths: coords,
        strokeColor: '#FF0000',
        strokeOpacity: 0.8,
        strokeWeight: 2,
        fillColor: '#FF0000',
        fillOpacity: 0.35
    });
    poly.setMap(map);
    return poly;
}


function getRandomArbitrary(min, max) {
    return Math.random() * (max - min) + min;
}