# Inner bounds of polygon in Leaflet

How can I find the inner bounds of a polygon in Leaflet? I a want to plot points randomly in polygon but when I say

``````Layer.getBounds()
``````

I get the bounds and I can still plot the markers approximately with in the saure i draw except most of them fall far out the intended polygons. This is because, `getBounds()` gives me out bounds.

Does any one have an idea how I can get inner bounds of a polygon?

• There isn't really a concept of an "inner bounds". Bounds are the maximum and minimum x and y (or lat and lon, x being lon) the polygon touches. Commented Oct 20, 2014 at 20:43
• Okay. So i can't possibly draw a square inside the polygon. Does this mean what i have is as close as am going to get to plotting random markers with in a district? Commented Oct 20, 2014 at 20:47
• You could use getLatLngs to get the vertices, generate points within the bounds, and use the even-odd rule en.wikipedia.org/wiki/Even%E2%80%93odd_rule to determine whether your points are inside the polygon. It would take a bit of scripting. Commented Oct 20, 2014 at 20:48
• following up on what @RussellatISC said, you could use something like Leaflet point in polygon in conjunction with getBounds(), to find points that only fall within the polygon.
– toms
Commented Oct 20, 2014 at 21:23
• Thanks @Russell and toms ... I should now be able to make my point more accurate. I will post my findings when I Finnaly get it plot accurately. Commented Oct 20, 2014 at 21:29

## 2 Answers

Mapbox has a pointinpolygon you could use. https://github.com/mapbox/leaflet-pip Layer must be: L.geoJSON layer

Then use something like :

``````var sw = polygon.getBounds().getSouthWest();
var ne = polygon.getBounds().getNorthEast();

for (var i = 0; i < 25; i++) {
var randomLat = Math.random() * (ne.lat() - sw.lat()) +sw.lat();
var randomLng = Math.random() * (ne.lng() - sw.lng()) +sw.lng();
var p = new L.latlng(randomLat, randomLng);
if (leafletPip.pointInLayer(p, polygon)) {
var mark = new L.marker(p).addTo(map);
break;
}
}
``````
• This can work, but the problem is that the random point is generated with a square box vs the actual polygon, so if the point is inside the bounding box, but outside the polygon itself, you'll need to call your function (in the example above, a loop) again until a match (pip) is found Commented Sep 15, 2015 at 18:01

I have done with below code:

``````function getPolygonBounds() {
var polygons = []
map.eachLayer(function (layer) {
if (layer instanceof L.Polygon && !(layer instanceof L.Rectangle)) {
polygons.push(layer.getLatLngs()) //Returns an array of arrays of geographical points in each polygon.
polygons.push(layer.getBounds()) //Returns a GeoJSON representation of the polygon (GeoJSON Polygon Feature).
}
})
return polygons
}
``````