mapbox - how to generate a random coordinate inside a polygon
Add a polygon
var polygon = L.polygon([ [51.509, -0.08], [51.503, -0.06], [51.51, -0.047] ]).addTo(map);
Get the bounds of the polygon
var bounds = polygon.getBounds();
Get the x and y limits of the bounds
var x_max = bounds.getEast(); var x_min = bounds.getWest(); var y_max = bounds.getSouth(); var y_min = bounds.getNorth();
Generate a random latitude within the y limits (see also this answer)
var lat = y_min + (Math.random() * (y_max - y_min));
Generate a random longitude within the x limits
var lng = x_min + (Math.random() * (x_max - x_min));
Use Turf.js to test if the point is within the polygon
var point = turf.point([lng, lat]); var poly = polygon.toGeoJSON(); var inside = turf.inside(point, poly);
If not, repeat.
All as one function. Be sure to include turf.js (minified)
// define the function
randomPointInPoly = function(polygon) {
var bounds = polygon.getBounds();
var x_min = bounds.getEast();
var x_max = bounds.getWest();
var y_min = bounds.getSouth();
var y_max = bounds.getNorth();
var lat = y_min + (Math.random() * (y_max - y_min));
var lng = x_min + (Math.random() * (x_max - x_min));
var point = turf.point([lng, lat]);
var poly = polygon.toGeoJSON();
var inside = turf.inside(point, poly);
if (inside) {
return point
} else {
return randomPointInPoly(polygon)
}
}
// create a poly
var polygon = L.polygon([
[51.509, -0.08],
[51.503, -0.06],
[51.51, -0.047]
]).addTo(map);
// get a geojson point from the function
var point = randomPointInPoly(polygon);
// .. or add it to the map directly from the result
L.geoJson(randomPointInPoly(polygon)).addTo(map);