How to add a random point inside a polygon in Goog

2019-06-08 05:26发布

问题:

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