5

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?

2 Answers 2

10
  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);
1

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/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.