Karen Nersesian
Karen Nersesian

Reputation: 46

Drawing polygons and each one must have a click event with google map API

I am dealing with an unusual problem. I am using google map API for drawing Polygons in the maps. My problem is that only the first one Polygon is working normally and firing event "click" works.

Here is my code, if you run the code snippet that you will see that only the first polygon is working normally the event click does not work on the others.

enter image description here

var map;
var infoWindow;
var listOfPolygons = [];

function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 5, 
    center: {lat: 24.886, lng: -70.268},
    mapTypeId: 'terrain'
  });

  //Drawing tool
  var drawingManager = new google.maps.drawing.DrawingManager({
    drawingMode: google.maps.drawing.OverlayType.MARKER,
    drawingControl: true,
    drawingControlOptions: {
      position: google.maps.ControlPosition.TOP_CENTER,
      drawingModes: ['marker', 'circle', 'polygon', 'polyline', 'rectangle']
    },
    markerOptions: {icon: 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png'},
    circleOptions: {
      fillColor: '#ffff00',
      fillOpacity: 1,
      strokeWeight: 5,
      clickable: false,
      editable: true,
      zIndex: 1
    }
  });
  drawingManager.setMap(map);

  google.maps.event.addListener(drawingManager, 'overlaycomplete', function(event) {
    if (event.type == 'polygon') {
      alert("Polygon Completed");
      listOfPolygons.push(new google.maps.Polygon({
        paths: event.overlay.getPath().getArray(),
        strokeColor: '#FF0000',
        strokeOpacity: 0.8,
        strokeWeight: 3,
        fillColor: '#FF0000',
        fillOpacity: 0.35
      }));
      listOfPolygons[listOfPolygons.length - 1].setMap(map);
      listOfPolygons[listOfPolygons.length - 1].addListener('click', showArrays);
      alert(listOfPolygons.length);
    }
  });

  infoWindow = new google.maps.InfoWindow();

}

/** @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>Bermuda Triangle polygon</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);
}
/* Always set the map height explicitly to define the size of the div
 * element that contains the map. */
#map {
  height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCe-f8ouEtRm_ZeprT8-WEKulMy99VmJYU&libraries=drawing&callback=initMap"
    async defer></script>

Upvotes: 2

Views: 3355

Answers (1)

geocodezip
geocodezip

Reputation: 161324

The polygon from the DrawingManager is on top of the Polygon with the click listener. You only want one version of the new Polygon, the one with the click listener added to it, hide the one from the DrawingManager (inside the overlaycomplete listener):

google.maps.event.addListener(drawingManager, 'overlaycomplete', function(event) {
  if (event.type == 'polygon') {
    // hide polygon from DrawingManager
    event.overlay.setMap(null);
    // ....... existing code ............

proof of concept fiddle

screenshot of resulting map

code snippet:

var map;
var infoWindow;
var listOfPolygons = [];

function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 5,
    center: {
      lat: 24.886,
      lng: -70.268
    },
    mapTypeId: 'terrain'
  });

  //Drawing tool
  var drawingManager = new google.maps.drawing.DrawingManager({
    drawingMode: google.maps.drawing.OverlayType.MARKER,
    drawingControl: true,
    drawingControlOptions: {
      position: google.maps.ControlPosition.TOP_CENTER,
      drawingModes: ['marker', 'circle', 'polygon', 'polyline', 'rectangle']
    },
    markerOptions: {
      icon: 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png'
    },
    circleOptions: {
      fillColor: '#ffff00',
      fillOpacity: 1,
      strokeWeight: 5,
      clickable: false,
      editable: true,
      zIndex: 1
    }
  });
  drawingManager.setMap(map);

  google.maps.event.addListener(drawingManager, 'overlaycomplete', function(event) {
    if (event.type == 'polygon') {
      console.log("Polygon Completed");
      // hide polygon from DrawingManager
      event.overlay.setMap(null);
      listOfPolygons.push(new google.maps.Polygon({
        paths: event.overlay.getPath().getArray(),
        strokeColor: '#FF0000',
        strokeOpacity: 0.8,
        strokeWeight: 3,
        fillColor: '#FF0000',
        fillOpacity: 0.35
      }));
      listOfPolygons[listOfPolygons.length - 1].setMap(map);
      listOfPolygons[listOfPolygons.length - 1].addListener('click', showArrays);
      console.log(listOfPolygons.length);

    }
  });

  infoWindow = new google.maps.InfoWindow();

}

/** @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>Bermuda Triangle polygon</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);
}
/* Always set the map height explicitly to define the size of the div
 * element that contains the map. */
#map {
  height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?libraries=drawing&callback=initMap"
    async defer></script>

Upvotes: 1

Related Questions