# mapbox - how to generate a random coordinate inside a polygon

I've seen the leaflet plugin for mapbox which finds the polygon within which a specific point / coordinate lies, but how would I do the opposite - generate a random point / coordinate within a specific polygon?

``````var polygon = L.polygon([
[51.509, -0.08],
[51.503, -0.06],
[51.51, -0.047]
``````
2. Get the bounds of the polygon

``````var bounds = polygon.getBounds();
``````
3. 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();
``````

``````var lat = y_min + (Math.random() * (y_max - y_min));
``````
5. Generate a random longitude within the x limits

``````var lng = x_min + (Math.random() * (x_max - x_min));
``````
6. 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);
``````
7. 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]

// get a geojson point from the function
var point = randomPointInPoly(polygon);

// .. or add it to the map directly from the result
``````

Based on the above answer, I have created a JS fiddle.. what does the example shows.

1. creates a mapbox map
2. adds a polygon to map
3. calculate bounds of poly
4. create a random point in poly, check with turf

https://jsfiddle.net/4c6qn20h/2/

Here is an up-to-date and more efficient version of @toms' answer.

``````import booleanPointInPolygon from '@turf/boolean-point-in-polygon';

const randomPointInPoly = (polygon, bounds) => {
const [x_min, y_min, x_max, y_max] = bounds;
let lat, lng;
while (true) {
lat = y_min + (Math.random() * (y_max - y_min));
lng = x_min + (Math.random() * (x_max - x_min));
if (booleanPointInPolygon([lng, lat], polygon)) {
return {lng, lat};
}
}
}
``````

Here `polygon` is already a GeoJSON, you will have to pass the `bounds` to it, and the return is an object.

• You should also be able to just use @turf/point-on-feature as a less involved solution that also works for `LineString`s. Commented Jul 2 at 13:43