I have a bounds to a place and created a polygon of that place. How can I generate a random point inside the bounds of that polygon?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
One way of doing it. This will calculate the bounds of the polygon, then guess a random point inside that bounds, if the point is contained by the polygon, it will put a marker there.
// 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