使用叠加完成功能获取多边形的区域

时间:2018-05-03 17:06:54

标签: javascript google-maps-api-3

我试图获取多边形的区域,问题是用户可以绘制多个多边形。

当overlaycomplete函数触发时,我似乎无法弄清楚如何实际引用刚刚制作的多边形。

此刻我有这个......

google.maps.event.addListener(drawingManager, 'overlaycomplete', function (e) {
    all_overlays.push(e);
    if (e.type == 'polygon') {
        //get the coordinate array of your polygon
        var area = google.maps.geometry.spherical.computeArea(polygon.getPath());
        console.log(area);
        var overallArea = overallArea + area;
        console.log(overallArea);

        // Switch back to non-drawing mode after drawing a shape.
        drawingManager.setDrawingMode(null);

    }
});

因此,当形状完成后,形状的细节将添加到数组中,以便以后可以从地图中清除它们。

但是,当我尝试计算区域时,我得到了这个......

ReferenceError:未定义多边形

为了引用并因此获取最近绘制的形状/多边形的区域,我实际需要做什么?

1 个答案:

答案 0 :(得分:-1)

多边形是e.overlay。用它来计算面积:

google.maps.event.addListener(drawingManager, 'overlaycomplete', function (e) {
  all_overlays.push(e);
  if (e.type == 'polygon') {
      //get the coordinate array of your polygon
      var area = google.maps.geometry.spherical.computeArea(e.overlay.getPath());
      console.log(area);
      overallArea = overallArea + area;
      console.log(overallArea);

      // Switch back to non-drawing mode after drawing a shape.
      drawingManager.setDrawingMode(null);
  }
});

proof of concept fiddle

代码段

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    center: {
      lat: -34.397,
      lng: 150.644
    },
    zoom: 8
  });
  var all_overlays = [];
  var overallArea = 0;
  var drawingManager = new google.maps.drawing.DrawingManager({
    drawingMode: google.maps.drawing.OverlayType.MARKER,
    drawingControl: true,
    drawingControlOptions: {
      position: google.maps.ControlPosition.TOP_CENTER,
      drawingModes: ['polygon']
    },
    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(e) {
    all_overlays.push(e);
    if (e.type == 'polygon') {
      //get the coordinate array of your polygon
      var area = google.maps.geometry.spherical.computeArea(e.overlay.getPath());
      console.log(area);
      overallArea = overallArea + area;
      console.log(overallArea);

      // Switch back to non-drawing mode after drawing a shape.
      drawingManager.setDrawingMode(null);

    }
  });
}
html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0;
  padding: 0;
}
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?libraries=drawing&callback=initMap" async defer></script>