Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the area string from a polygon using leaflet.draw

I am trying to get the area measurements of polygons so I can list them in a table to the side of the map, next to the name of the polygon. This is what I have tried with no success:

$("#polygon").on("click", function (){
    createPolygon = new L.Draw.Polygon(map, drawControl.options.polygon);
    createPolygon.enable();
}

var polygon = new L.featureGroup();

map.on('draw:created', function (e) {
    var type = e.layerType,
        layer = e.layer;
    if (type === 'polygon') {
      polygons.addLayer(layer);
    }
    var seeArea = createPolygon._getMeasurementString();
   console.log(seeArea);  //Returns null
}

Any help on this would be appreciated!

like image 602
Marty.H Avatar asked Apr 19 '15 01:04

Marty.H


People also ask

How do you find the center of a polygon in a leaflet?

call one point of the polygon, then offset the position of the popup. Use an id for each polygon, so each popup knows the box area (polygon) it can be opened in.

How do you draw a polygon in a leaflet map?

Create a polygon using the L. Pass the locations/points as variable to draw the polygon, and an option to specify the color of the polygon. var polygon = L. polygon(latlngs, {color: 'red'}); Add the polygon to the map using the addTo() method of the Polygon class.

How do you use a leaflet draw plugin?

To use the Leaflet. draw plugin, you need to add the js and css files to your html header, like so: <! DOCTYPE html> <html> <head> <meta charset="UTF-8"> <!

How do you know if a point is inside a polygon leaflet?

Click on the map or the markers and a pop-up will show indicating if the point you clicked on, or the marker, is in the polygon. Leaflet.


2 Answers

You can access the geometry utility library provided with Leaflet.

var area = L.GeometryUtil.geodesicArea(layer.getLatLngs());

In your example, you are trying to access a control itself, which is what the variable createPolygon is assigned to. Instead, you want to take the area of the layer that got drawn.

map.on('draw:created', function (e) {
  var type = e.layerType,
      layer = e.layer;
  if (type === 'polygon') {
    polygons.addLayer(layer);
    var seeArea = L.GeometryUtil.geodesicArea(layer.getLatLngs());
    console.log(seeArea);
  }
}

Once you verify you are getting the area, you can just assign it to the variables that populate the table next to the map.

Note: area will be in squareMeters by default

like image 85
The Brofessor Avatar answered Oct 13 '22 19:10

The Brofessor


L.GeometryUtil.geodesicArea(layer.getLatLngs())[0] should get you the area.

But I ended up using leaflet-geoman-free to do the drawing and use turf.js to get the area.

map.pm.enableDraw('Polygon', {
   snappable: true,
   snapDistance: 20,
});

map.on('pm:create', e => {
   const layer = e.layer
   alert(turf.area(layer.toGeoJSON()))
});
like image 43
KuN Avatar answered Oct 13 '22 18:10

KuN