3
\$\begingroup\$

I want to display multiple polygons (with the co ordinates either given by the user or pre-defined) on Google Maps and to toggle the visibility of each polygon. I wrote the code to display multiple polygons by manually entering all the longitudes and latitudes values.

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Multi Polygon</title>
    <style>
      html, body, #map-canvas {
        height: 700px;
        margin: 0px;
        padding: 0px
      }
    </style>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
    <script>

var map;
var infoWindow;

function initialize() {
  var mapOptions = {
    zoom: 11,
    center: new google.maps.LatLng(41.8500,-87.9645),
  };

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

  infoWindow = new google.maps.InfoWindow();

   var marker = new google.maps.Marker({position:new google.maps.LatLng(41.7508, -88.1535)});
   marker.setMap(map);
   // Construct the polygon.
  var multiPolygon1 = new google.maps.Polygon({
    paths: [
         new google.maps.LatLng(41.769007157585534,-88.20167541503906), 
    new google.maps.LatLng(41.76081263047197,-88.12236785888672), 
    new google.maps.LatLng( 41.717517926019624,-88.19429397583008)],
    strokeColor: '#ff987b',
    strokeOpacity: 0.8,
    strokeWeight: 3,
    fillColor: '#ff987b',
    fillOpacity: 0.35,
    name: 'Polygon 1', 
        map: map
  });

  // Add a listener for the click event.
  google.maps.event.addListener(multiPolygon1, 'click', showArrays);

  var marker1 = new google.maps.Marker({position:new google.maps.LatLng(41.8661, -88.1070)});
   marker1.setMap(map);
  // Construct the polygon.
 var multiPolygon2 = new google.maps.Polygon({
    paths: [
      new google.maps.LatLng(41.88336502279732,-88.09249877929688), 
    new google.maps.LatLng(41.88157575821145,-88.12957763671875), 
    new google.maps.LatLng( 41.84271080015277,-88.12408447265625),
    new google.maps.LatLng( 41.841431946284025,-88.08425903320312)],
    strokeColor: '#ff987b',
    strokeOpacity: 0.8,
    strokeWeight: 3,
    fillColor: '#ff987b',
    fillOpacity: 0.35,
     name: 'Polygon 2',
     map:map
  });

  // Add a listener for the click event.
  google.maps.event.addListener(multiPolygon2, 'click', showArrays);

   var marker2 = new google.maps.Marker({position:new google.maps.LatLng(41.9103, -88.0717)});
   marker2.setMap(map);

  var multiPolygon3 = new google.maps.Polygon({
    paths: [
      new google.maps.LatLng(41.96051129429776,-88.12957763671875), 
    new google.maps.LatLng(41.93906275484857, -88.00048828125), 
    new google.maps.LatLng(41.884387437207835, -88.02314758300781),
    new google.maps.LatLng(41.879275201550634, -88.07395935058594),
    new google.maps.LatLng(41.948766559468574, -88.11172485351562)],
    strokeColor: '#FF0000',
    strokeOpacity: 0.8,
    strokeWeight: 3,
    fillColor: '#FF0000',
    fillOpacity: 0.35,
     name: 'Polygon 3',
     map:map
  });

  // Add a listener for the click event.
  google.maps.event.addListener(multiPolygon3, 'click', showArrays);

  var marker3 = new google.maps.Marker({position:new google.maps.LatLng(41.79179268262892, -88.07601928710938)});
   marker3.setMap(map);

  var multiPolygon4 = new google.maps.Polygon({
    paths: [
      new google.maps.LatLng(41.80203073088394, -88.09730529785156), 
    new google.maps.LatLng(41.801006999656636, -88.07533264160156), 
    new google.maps.LatLng(41.74313962010849, -88.05301666259766)],
    strokeColor: '#FF0000',
    strokeOpacity: 0.8,
    strokeWeight: 3,
    fillColor: '#FF0000',
    fillOpacity: 0.35,
     name: 'Polygon 4',
     map:map
  });

  // Add a listener for the click event.
  google.maps.event.addListener(multiPolygon4, 'click', showArrays);

  var marker4 = new google.maps.Marker({position:new google.maps.LatLng(41.9231, -87.7093)});
   marker4.setMap(map);

  var multiPolygon5 = new google.maps.Polygon({
    paths: [
    new google.maps.LatLng(41.901254912872794, -87.94418334960938), 
    new google.maps.LatLng(41.949277245116555, -87.92015075683594), 
    new google.maps.LatLng(41.93446570034958, -87.87895202636719),
    new google.maps.LatLng(41.96459591213679, -87.82608032226562),
    new google.maps.LatLng(41.9753167881278, -87.78968811035156),
    new google.maps.LatLng(41.899721690058364, -87.83706665039062),
    new google.maps.LatLng(41.937019660425264, -87.72239685058594),
    new google.maps.LatLng(41.87569639323101, -87.63175964355469)],
    strokeColor: '#FF0000',
    strokeOpacity: 0.8,
    strokeWeight: 3,
    fillColor: '#FF0000',
    fillOpacity: 0.35,
     name: 'Polygon 5',
     map:map
  });

  // Add a listener for the click event.
  google.maps.event.addListener(multiPolygon5, 'click', showArrays);

  var marker5 = new google.maps.Marker({position:new google.maps.LatLng(41.8050, -87.8692)});
   marker5.setMap(map);

  var multiPolygon6 = new google.maps.Polygon({
    paths: [
    new google.maps.LatLng(41.780016905285535, -87.95448303222656), 
    new google.maps.LatLng(41.83171182161546, -87.96066284179688), 
    new google.maps.LatLng(41.83273506215261, -87.94281005859375),
    new google.maps.LatLng(41.81073178596061, -87.88925170898438),
    new google.maps.LatLng(41.81226714359981, -87.78282165527344),
    new google.maps.LatLng(41.87723019276536, -87.77114868164062),
    new google.maps.LatLng(41.782577040867636, -87.74848937988281),
    new google.maps.LatLng(41.77182378456081, -87.88581848144531),
    new google.maps.LatLng(41.801006999656636, -87.9290771484375)],
    strokeColor: '#FF0000',
    strokeOpacity: 0.8,
    strokeWeight: 3,
    fillColor: '#FF0000',
    fillOpacity: 0.35,
     name: 'Polygon 6',
     map:map
  });

  // Add a listener for the click event.
  google.maps.event.addListener(multiPolygon6, 'click', showArrays);

  var marker6 = new google.maps.Marker({position:new google.maps.LatLng(41.7200, -87.7480)});
   marker6.setMap(map);

  var multiPolygon7 = new google.maps.Polygon({
    paths: [
    new google.maps.LatLng(41.852173524388824, -87.62489318847656), 
    new google.maps.LatLng(41.70880422215806, -87.62283325195312), 
    new google.maps.LatLng(41.70829161455626, -88.0059814453125),
    new google.maps.LatLng(41.74416427530836, -87.96821594238281),
    new google.maps.LatLng(41.73545418490723, -87.91603088378906),
    new google.maps.LatLng(41.735966575868716, -87.68051147460938),
    new google.maps.LatLng(41.840920397579936, -87.67707824707031)],
    strokeColor: '#FF0000',
    strokeOpacity: 0.8,
    strokeWeight: 3,
    fillColor: '#FF0000',
    fillOpacity: 0.35,
     name: 'Polygon 7',
     map:map
  });

  // Add a listener for the click event.
  google.maps.event.addListener(multiPolygon7, 'click', showArrays);
}

/** @this {google.maps.Polygon} */
function showArrays(event) {

  // Since this polygon has only one path, we can call getPath()
  // to return the MVCArray of LatLngs.
  var vertices = this.getPath();

  var contentString = '<b>' + this.name + '</b>';
  // '<br>' +
  //     'Clicked location: <br>' + event.latLng.lat() + ',' + event.latLng.lng() +
  //     '<br>';

  // Iterate over the vertices.
  // for (var i =0; i < vertices.getLength(); i++) {
  //   var xy = vertices.getAt(i);
  //   contentString += '<br>' + 'Coordinate ' + i + ':<br>' + xy.lat() + ',' +
  //       xy.lng();
  // }

  // Replace the info window's content and position.
  infoWindow.setContent(contentString);
  infoWindow.setPosition(event.latLng);

  infoWindow.open(map);
}

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

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

But the code is too lengthy and inefficient. How can I make my code object oriented and reduce the repetitive code? I tried using function to reduce the code but it did not work.

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Multi Polygon</title>
    <style>
      html, body, #map-canvas {
        height: 700px;
        margin: 0px;
        padding: 0px
      }
    </style>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
    <script>

var path1 = [
  [41.769007157585534,-88.20167541503906],
  [41.76081263047197,-88.12236785888672],
  [41.717517926019624,-88.19429397583008]];

var path2 = [
  [41.88336502279732,-88.09249877929688],
  [41.88157575821145,-88.12957763671875],
  [41.84271080015277,-88.12408447265625],
  [41.841431946284025,-88.08425903320312]];

var path3 = [
  [41.96051129429776,-88.12957763671875],
  [41.93906275484857, -88.00048828125],
  [41.884387437207835, -88.02314758300781],
  [41.879275201550634, -88.07395935058594],
  [41.948766559468574, -88.11172485351562]];

var path4 = [
  [41.80203073088394, -88.09730529785156],
  [41.801006999656636, -88.07533264160156],
  [41.74313962010849, -88.05301666259766]];

var path5 = [
  [41.901254912872794, -87.94418334960938],
  [41.949277245116555, -87.92015075683594],
  [41.93446570034958, -87.87895202636719],
  [41.96459591213679, -87.82608032226562],
  [41.9753167881278, -87.78968811035156],
  [41.899721690058364, -87.83706665039062],
  [41.937019660425264, -87.72239685058594],
  [41.87569639323101, -87.63175964355469]];

var path6 = [
  [41.780016905285535, -87.95448303222656],
  [41.83171182161546, -87.96066284179688],
  [41.83273506215261, -87.94281005859375],
  [41.81073178596061, -87.88925170898438],
  [41.81226714359981, -87.78282165527344],
  [41.87723019276536, -87.77114868164062],
  [41.782577040867636, -87.74848937988281],
  [41.77182378456081, -87.88581848144531],
  [41.801006999656636, -87.9290771484375]];

var path7 = [
  [41.852173524388824, -87.62489318847656],
  [41.70880422215806, -87.62283325195312],
  [41.70829161455626, -88.0059814453125],
  [41.74416427530836, -87.96821594238281],
  [41.73545418490723, -87.91603088378906],
  [41.735966575868716, -87.68051147460938],
  [41.840920397579936, -87.67707824707031]];

function mapToLatLng(source, index, array) {
  return new google.maps.LatLng(source[0], source[1])
}

function toLatLng(array) {
  return array.map(mapToLatLng);
}

function newPolyOptions(path) {
  return new google.maps.Polygon({
    path:path,
    strokeColor:"FF0000",
    strokeOpacity:0,
    strokeWeight:3,
    fillColor:"#94C11F",
    fillOpacity:0.5,
    clickable:false
  });
}

function newPolyLine(polyOptions) {
  var polyLine = new google.maps.Polyline(polyOptions);
  polyLine.setMap(map);
  return polyLine;
}

var poly1 = newPolyLine(newPolyOptions(toLatLng(path1)));
var poly2 = newPolyLine(newPolyOptions(toLatLng(path2)));
var poly3 = newPolyLine(newPolyOptions(toLatLng(path3)));
var poly4 = newPolyLine(newPolyOptions(toLatLng(path4)));
var poly5 = newPolyLine(newPolyOptions(toLatLng(path5)));
var poly6 = newPolyLine(newPolyOptions(toLatLng(path6)));
var poly7 = newPolyLine(newPolyOptions(toLatLng(path7)));

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

Also, I want to toggle the visibility of each polygon using checkbox. I tried doing that and the code works perfectly fine for only 1 polygon. However, if I apply for multiple polygons, it doesn't work.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
    <style>
    html, body, #map-canvas{
        height: 100%; 
        margin: 0px; 
        padding: 0px; 
        height: 590px;} 
        </style>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
    <!-- Include jQuery -->
    <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
    <script>

        // Move map declaration
        var map;

        function toggleLayer(toggleLayer,id)
        {
            if ($('#'+id).is(':checked')) {
                toggleLayer.setMap(map);
            }
            else
            {
                toggleLayer.setMap(null);
            }
        }

        function initialize() {
            var mapOptions = {
                zoom: 11,
                center: new google.maps.LatLng(41.8500,-87.9645),
              //  mapTypeId: google.maps.MapTypeId.TERRAIN
            };

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

            var marker = new google.maps.Marker({position:new google.maps.LatLng(41.7508, -88.1535)});
            marker.setMap(map);

           poly1 = new google.maps.Polygon({
                path: [
                new google.maps.LatLng(41.769007157585534,-88.20167541503906), 
                new google.maps.LatLng(41.76081263047197,-88.12236785888672), 
                new google.maps.LatLng( 41.717517926019624,-88.19429397583008)],
                strokeColor: '#FF0000',
                strokeOpacity: 0.8,
                strokeWeight: 3,
                fillOpacity: 0.1,
                fillColor: '#ff987b',
                fillOpacity: 0.35,
                name: 'Polygon 2',
            map:map
            });

        }
        google.maps.event.addDomListener(window, 'load', initialize);
    </script>
</head>
<body>
<div id="map-canvas"></div>
<input id="togglepoly1" type="checkbox" checked="yes" onClick="toggleLayer(poly1,'togglepoly1')" /> Polygon 1
</body>
</html>
\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

If you want to use checkboxes to toggle polygons, you can set a user-defined properties when you creating a new polygon. For example:

var polygon = new google.maps.Polygon({
        paths: data.location,
        fillColor: '#6c757d',
        fillOpacity: 0.4,
        strokeWeight: 0,
        strokeOpacity: 0,
        clickable: true,
        markers: [],
        treeMap: new Map(),
        name: data.name,
        manager: data.manager,
        id: data.id,
        density_color: '#6c757d'
    });

The last 6 properties are user-defined so that you can add ID property for each polygon and toggle them using setMap(Null).

Ps: You should put all your polygons in an array for better manipulating.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.