创建形状时,我具有此事件侦听器:



// This example requires the Drawing library. Include the libraries=drawing
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=drawing">

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    center: {lat: -33.872, lng: 151.252},
    zoom: 6
  });

  var drawingManager = new google.maps.drawing.DrawingManager({
    drawingMode: google.maps.drawing.OverlayType.POLYGON,
    drawingControl: false,
    drawingControlOptions: {
      position: google.maps.ControlPosition.TOP_LEFT,
      drawingModes: []
    },
    polygonOptions: {
      fillColor: 'rgba(255, 0, 0, 0.2)',
      fillOpacity: 1,
      strokeWeight: 2,
      clickable: true,
      editable: true,
      zIndex: 1
    }
  });

  drawingManager.setMap(map);
  // Define the LatLng coordinates for the outer path.
  var outerCoords = [
    {lat: -25.364, lng: 155.207}, // north west
    {lat: -35.364, lng: 155.207}, // south west
    {lat: -35.364, lng: 148.207}, // south east
    {lat: -25.364, lng: 148.207}  // north east
  ];


  map.data.add({geometry: new google.maps.Data.Polygon([outerCoords])});


google.maps.event.addListener(drawingManager, 'overlaycomplete', function(event) {
    if(event.type == 'polygon') {
       var verticles = event.overlay.getPaths();

      verticles.forEach(function(verticle, ind){
      console.log({
        "index": ind,
        "lat": verticle.getAt(ind).lat(),
        "lng": verticle.getAt(ind).lng(),
        "obj": verticle.getAt(ind)
      });
      });
    }


});


}

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <style>
    html, body {
    height: 100%;
    margin: 0;
    padding: 0;
    }
    #map {
      height: 100%;
    }
  </style>
</head>
<body>
<div id="map"></div>
<div id="capture"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBFOolEMjIlnlkVle8gsiDA1ym3aktxEGc&libraries=drawing&callback=initMap"
         async defer></script>
</body>
</html>





但是,无论Polygon包含多少行,.getPaths()似乎仅返回一组经纬度。从文档看来,它应该返回一个对象数组,其中每个对象都是绘制直线所需的两个点(纬度/经度)的数组。我想念什么?

最佳答案

更改

var verticles = event.overlay.getPaths();


为了这:

var verticles = event.overlay.getPath().getArray()

09-12 15:00