【问题标题】:Drawing polygons and each one must have a click event with google map API绘制多边形,每个多边形都必须有一个带有谷歌地图 API 的点击事件
【发布时间】:2018-03-26 13:59:13
【问题描述】:

我正在处理一个不寻常的问题。我正在使用谷歌地图 API 在地图中绘制多边形。我的问题是只有第一个 Polygon 工作正常,并且触发事件“click”有效。

这是我的代码,如果你运行代码 sn-p 你会看到只有第一个多边形正常工作,事件点击在其他多边形上不起作用。

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>

【问题讨论】:

    标签: javascript google-maps


    【解决方案1】:

    来自DrawingManager 的多边形位于带有点击侦听器的多边形顶部。您只需要新多边形的一个版本,即添加了单击侦听器的版本,将其隐藏在DrawingManager 中(在overlaycomplete 侦听器内):

    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

    代码 sn-p:

    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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-29
      • 1970-01-01
      • 2015-08-26
      • 1970-01-01
      • 1970-01-01
      • 2013-02-18
      • 1970-01-01
      相关资源
      最近更新 更多