Google 地图 API 显示绘制多边形内部的标记

Google map API show markers inside of draw polygon

我正在尝试在绘制多边形内显示标记。示例:如果用户在 google 地图上绘制多边形,我想显示绘制多边形的标记。我正在考虑绘制多边形。我还附上了此代码的屏幕显示,以便您轻松理解。

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

function initMap() {
  var locations =[
        [41.599013054830216, -110.006103515625],
        [41.566141964768384, -107.501220703125],
        [41.64007838467894, -104.61181640625],
        [41.66470503009207, -101.590576171875],
        [40.39676430557203, -100.821533203125],
        [38.66835610151509, -100.634765625],
        [36.97622678464096, -100.8544921875],
        [36.049098959065645, -101.239013671875],
        [36.155617833818525, -104.150390625],
        [35.92464453144099, -106.951904296875],
        [36.08462129606931, -110.0390625],
        [37.58811876638322, -110.45654296875],
        [40.44694705960048, -110.14892578125],
        [40.49709237269567, -108.160400390625],
        [40.49709237269567, -104.468994140625],
        [40.50544628405211, -102.843017578125],
        [39.342794408952386, -103.348388671875],
        [39.8928799002948, -105.567626953125],
        [38.99357205820946, -105.963134765625],
        [37.97884504049713, -103.941650390625],
        [37.413800350662896, -103.02978515625],
        [37.448696585910376, -104.83154296875],
        [37.29153547292737, -107.42431640625],
        [37.68382032669382, -108.5009765625],
        [38.453588708941375, -107.149658203125]
    ];
  var markers = [];
  map = new google.maps.Map(document.getElementById("map"), {
    center: new google.maps.LatLng(39.01064750994083, -105.6390380859375),
    zoom: 10,
    streetViewControl: false,
    mapTypeControl: false
  });
    //Drawing tool
    var drawingManager = new google.maps.drawing.DrawingManager({
      drawingMode: google.maps.drawing.OverlayType.MARKER,
      drawingControl: true,
      drawingControlOptions: {
        
        position: google.maps.ControlPosition.LEFT_TOP,
        drawingModes: [
         // google.maps.drawing.OverlayType.MARKER,
          //google.maps.drawing.OverlayType.CIRCLE,
          google.maps.drawing.OverlayType.POLYGON,
          //google.maps.drawing.OverlayType.POLYLINE,
         google.maps.drawing.OverlayType.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);
    for (i = 0; i < locations.length; i++) { 
      markers.push(
        new google.maps.Marker({
          position: {lat: locations[i][0], lng: locations[i][1]},
          map: map
        })
      );
    }
    google.maps.event.addListener(drawingManager, 'overlaycomplete', function(event) {
      var poly = event.overlay.getPath();
      if (event.type == 'polygon') {
        
        console.log("Polygon Completed");
        
        // hide polygon from DrawingManager
        event.overlay.setMap(null);
        //console.log(event.overlay.getPath().getArray());
        listOfPolygons.push(new google.maps.Polygon({
          paths: event.overlay.getPath().getArray(),
          strokeColor: '#FF0000',
          strokeOpacity: 0.8,
          strokeWeight: 3,
          fillColor: '#FF0000',
          fillOpacity: 0.35
        }));
        console.log(listOfPolygons);
        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.
  console.log(contentString);
  infoWindow.setContent(contentString);
  infoWindow.setPosition(event.latLng);

  infoWindow.open(map);
}
google.maps.event.addDomListener(window, "load", initMap);

}

请检查此屏幕是否显示我需要的内容。

desired results

  1. 创建时隐藏所有标记(不要设置地图变量,visible设置为false)。
for (i = 0; i < locations.length; i++) {
  markers.push(
    new google.maps.Marker({
      position: {
        lat: locations[i][0],
        lng: locations[i][1]
      },
    })
  );
}
  1. 在创建每个多边形时对其进行处理,显示它包含的所有标记。
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(event) {
  var poly = event.overlay.getPath();
  if (event.type == 'polygon') {
    // 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
    }));
    for (var i = 0; i < markers.length; i++) {
      if (google.maps.geometry.poly.containsLocation(markers[i].getPosition(), listOfPolygons[listOfPolygons.length - 1])) {
        // show current marker
        markers[i].setMap(map);
      }
    }
    listOfPolygons[listOfPolygons.length - 1].setMap(map);
  }
});

proof of concept fiddle

代码片段:

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

function initMap() {
  var locations = [
    [41.599013054830216, -110.006103515625],
    [41.566141964768384, -107.501220703125],
    [41.64007838467894, -104.61181640625],
    [41.66470503009207, -101.590576171875],
    [40.39676430557203, -100.821533203125],
    [38.66835610151509, -100.634765625],
    [36.97622678464096, -100.8544921875],
    [36.049098959065645, -101.239013671875],
    [36.155617833818525, -104.150390625],
    [35.92464453144099, -106.951904296875],
    [36.08462129606931, -110.0390625],
    [37.58811876638322, -110.45654296875],
    [40.44694705960048, -110.14892578125],
    [40.49709237269567, -108.160400390625],
    [40.49709237269567, -104.468994140625],
    [40.50544628405211, -102.843017578125],
    [39.342794408952386, -103.348388671875],
    [39.8928799002948, -105.567626953125],
    [38.99357205820946, -105.963134765625],
    [37.97884504049713, -103.941650390625],
    [37.413800350662896, -103.02978515625],
    [37.448696585910376, -104.83154296875],
    [37.29153547292737, -107.42431640625],
    [37.68382032669382, -108.5009765625],
    [38.453588708941375, -107.149658203125]
  ];
  var markers = [];
  map = new google.maps.Map(document.getElementById("map"), {
    center: new google.maps.LatLng(39.01064750994083, -105.6390380859375),
    zoom: 10,
    streetViewControl: false,
    mapTypeControl: false
  });
  //Drawing tool
  var drawingManager = new google.maps.drawing.DrawingManager({
    drawingMode: google.maps.drawing.OverlayType.POLYGON,
    drawingControl: true,
    drawingControlOptions: {
      position: google.maps.ControlPosition.LEFT_TOP,
      drawingModes: [
        google.maps.drawing.OverlayType.POLYGON,
      ],
    }
  })
  drawingManager.setMap(map);
  var bounds = new google.maps.LatLngBounds();
  for (i = 0; i < locations.length; i++) {
    markers.push(
      new google.maps.Marker({
        position: {
          lat: locations[i][0],
          lng: locations[i][1]
        },
      })
    );
    bounds.extend(markers[markers.length - 1].getPosition());
  }
  map.fitBounds(bounds);
  google.maps.event.addListener(drawingManager, 'overlaycomplete', function(event) {
    var poly = event.overlay.getPath();
    if (event.type == 'polygon') {
      // hide polygon from DrawingManager
      event.overlay.setMap(null);
      //console.log(event.overlay.getPath().getArray());
      listOfPolygons.push(new google.maps.Polygon({
        paths: event.overlay.getPath().getArray(),
        strokeColor: '#FF0000',
        strokeOpacity: 0.8,
        strokeWeight: 3,
        fillColor: '#FF0000',
        fillOpacity: 0.35
      }));
      for (var i = 0; i < markers.length; i++) {
        if (google.maps.geometry.poly.containsLocation(markers[i].getPosition(), listOfPolygons[listOfPolygons.length - 1])) {
          // show current marker
          markers[i].setMap(map);
        }
      }
      listOfPolygons[listOfPolygons.length - 1].setMap(map);
      listOfPolygons[listOfPolygons.length - 1].addListener('click', showArrays);
    }
  });

  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>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.
    console.log(contentString);
    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;
}
<!DOCTYPE html>
<html>

<head>
  <title>Drawing Tools</title>
  <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
  <!-- jsFiddle will insert css and js -->
</head>

<body>
  <div id="map"></div>

  <!-- Async script executes immediately and must be after any DOM elements used in callback. -->
  <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&libraries=drawing,geometry&v=weekly&channel=2" async></script>
</body>

</html>