如何在Google Maps中的多边形内添加随机点?

时间:2014-04-04 02:19:55

标签: google-maps-api-3 google-maps-markers google-polyline

我有一个地方的边界,并创建了该地方的多边形。 如何在该多边形的边界内生成随机点?

1 个答案:

答案 0 :(得分:6)

一种方法。这将计算多边形的边界,然后猜测该边界内的随机点,如果该点包含在多边形中,它将在那里放置一个标记。

// calculate the bounds of the polygon
var bounds = new google.maps.LatLngBounds();

for (var i=0; i < polygon.getPath().getLength(); i++) {
    bounds.extend(polygon.getPath().getAt(i));
}

var sw = bounds.getSouthWest();
var ne = bounds.getNorthEast();

// Guess 100 random points inside the bounds, 
// put a marker at the first one contained by the polygon and break out of the loop
for (var i = 0; i < 100; i++) {
   var ptLat = Math.random() * (ne.lat() - sw.lat()) + sw.lat();
   var ptLng = Math.random() * (ne.lng() - sw.lng()) + sw.lng();
   var point = new google.maps.LatLng(ptLat,ptLng);
   if (google.maps.geometry.poly.containsLocation(point,polygon)) {
     var marker = new google.maps.Marker({position:point, map:map});
     break;
   }
}

working fiddle

working fiddle with up to 100 random points