Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

checking size of Polygon drawn with Leaflet l.draw.polyline

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?

like image 762
user2724836 Avatar asked Aug 28 '13 09:08

user2724836


3 Answers

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())
                ...
like image 131
Rami Avatar answered Nov 13 '22 18:11

Rami


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.

like image 1
Patrick D Avatar answered Nov 13 '22 19:11

Patrick D


You can use GeometryUtil.geodesicArea() to the get the area like this:

let area = L.GeometryUtil.geodesicArea(layer.getLatLngs()[0]);
like image 1
Ben Ayoub Avatar answered Nov 13 '22 19:11

Ben Ayoub