how to calculate number of markers inside a polygon in google maps

前端 未结 1 1921
灰色年华
灰色年华 2021-01-03 17:15

Looking for a way to count the number of markers inside a polygon which is drawn dynamically by the user

The code below can draw the polygon now i want to show the c

相关标签:
1条回答
  • 2021-01-03 17:56
    1. keep references to your markers in an array
    2. iterate through that array using google.maps.geometry.poly.containsLocation(latLng,polygon) to determine if the marker is in the polygon or not
    3. output the result.

    proof of concept fiddle

    code snippet:

    function initMap() {
      var mapOptions = {
        center: {
          lat: 27.174977,
          lng: 78.042064
        },
        zoom: 8
      };
      var map15 = new google.maps.Map(document.getElementById("map"), mapOptions);
      var markers = []
      google.maps.event.addListenerOnce(map15, 'bounds_changed', function() {
        function getRandom(min, max) {
          return Math.random() * (max - min + 1) + min;
        }
        var bounds = map15.getBounds();
        for (var j = 0; j < 30; j++) {
    
          var marker = new google.maps.Marker({
            position: new google.maps.LatLng(getRandom(bounds.getSouthWest().lat(), bounds.getNorthEast().lat()),
              getRandom(bounds.getSouthWest().lng(), bounds.getNorthEast().lng())),
            map: map15
          });
          markers.push(marker);
        }
    
      })
    
      var polygon = new google.maps.Polygon({
        strokeColor: "#1E41AA",
        strokeOpacity: 1.0,
        strokeWeight: 3,
        map: map15,
        fillColor: "#2652F2",
        fillOpacity: 0.6
      });
    
      var poly = polygon.getPath();
    
      function addPolyPoints(e) {
        poly.push(e.latLng);
        var markerCnt = 0;
        for (var i = 0; i < markers.length; i++) {
          if (google.maps.geometry.poly.containsLocation(markers[i].getPosition(), polygon)) {
            markerCnt++;
          }
        }
        document.getElementById('info').innerHTML = "markers in polygon: " + markerCnt;
      }
    
      google.maps.event.addListener(map15, 'click', addPolyPoints);
    }
    
    google.maps.event.addDomListener(window, "load", initMap);
    html,
    body,
    #map {
      height: 100%;
      width: 100%;
      margin: 0px;
      padding: 0px
    }
    <script src="https://maps.googleapis.com/maps/api/js?libraries=geometry&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
    <div id="info"></div>
    <div id="map"></div>

    0 讨论(0)
提交回复
热议问题