I've made a website with Leaflet to draw polygons on an OSM-Map
.
Now I want to check the size of the polygon, because the polygon must not exceed a defined size, for example, 5 square kilometers.
Does anyone have a good idea to check the size of the drawn polygon?
I have used leaflet.draw ( https://github.com/Leaflet/Leaflet.draw ) to draw a polygon.
And it has geodesicArea function. Sample in 'draw:created'.
map.on('draw:created', function (e) {
var type = e.layerType,
layer = e.layer;
if (type === 'polygon')
{
var area = L.GeometryUtil.geodesicArea(layer.getLatLngs())
...
I do not know of any Leaflet plugins that can accomplish this for you. However, the algorithm to do so is not terribly complex. Check this website: http://www.mathopenref.com/coordpolygonarea2.html that contains the algorithm, and many visual examples as to how the algorithm actually works.
function polygonArea(X, Y, numPoints)
{
area = 0; // Accumulates area in the loop
j = numPoints-1; // The last vertex is the 'previous' one to the first
for (i=0; i<numPoints; i++)
{ area = area + (X[j]+X[i]) * (Y[j]-Y[i]);
j = i; //j is previous vertex to i
}
return area/2;
}
In order to use this algorithm with Leaflet polygons, you would iterate through the Polygon polygon.getLatLngs()
in order to get all the lat/lon pairs. Put them into two separate arrays - one for X coordinates, one for Y coordinates. Use these as parameters to the function above, and for numPoints
hand it the polygon.getLatLngs().length
As the webpage says, it doesn't matter where on the polygon path this starts. However, if you begin in a counter-clockwise order, your result will be negative. You can handle all cases by simply getting the absolute value of whatever this function returns.
You can use GeometryUtil.geodesicArea()
to the get the area like this:
let area = L.GeometryUtil.geodesicArea(layer.getLatLngs()[0]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With