# 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