寻找一种方法来计算由用户动态绘制的多边形内部的标记数量
下面的代码现在可以绘制多边形我想要显示多边形内部的标记数量(如果存在)
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Simple Polygon</title>
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
width: 100%;
}
</style>
</head>
<body>
<div id="map"></div>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.17&AIzaSyBLnIMoOLvgLaeIUEzLX3sIw0-FOXwXcag"> </script>
<script>
function initMap() {
var mapOptions={
center:{lat: 27.174977,lng:78.042064},
zoom: 8
};
var map15= new google.maps.Map(document.getElementById("map"),mapOptions);
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);
}
google.maps.event.addListener(map15,'click',addPolyPoints);
}
initMap();
</script>
</body>
</html>
即,当用户绘制多边形时,如果存在标记,则应提供计数。
怎么做?
答案 0 :(得分:6)
google.maps.geometry.poly.containsLocation(latLng,polygon)
遍历该数组以确定标记是否在多边形中代码段
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);
&#13;
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
&#13;
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="info"></div>
<div id="map"></div>
&#13;