mapbox - how to generate a random coordinate inside a polygon

  1. Add a polygon

    var polygon = L.polygon([
        [51.509, -0.08],
        [51.503, -0.06],
        [51.51, -0.047]
    ]).addTo(map);
    
  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();
    
  4. Generate a random latitude within the y limits (see also this answer)

    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]
]).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);