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

后端 未结 4 1534
温柔的废话
温柔的废话 2020-12-18 21:58

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 n

相关标签:
4条回答
  • 2020-12-18 22:07

    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()))
    });
    
    0 讨论(0)
  • 2020-12-18 22:14

    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

    0 讨论(0)
  • 2020-12-18 22:25

    I found that none of the above answers worked for calculating the area of non-contiguous polygons. Here's an example polygon where the above functions returned an area of 0:

    For anyone who needs to do that, here is the code that worked for me (using the L.GeometryUtil function from Leaflet.draw):

    var poly = // Your polygon layer here; may or may not be contiguous
    var area = 0;
    for (island of poly.getLatLngs()) {
        // If the polygon is non-contiguous, access the island
        if (island.length < 2) {
            island = island[0]
        }
        // Sum the area within each "island"
        area += L.GeometryUtil.geodesicArea(island);
    }

    0 讨论(0)
  • 2020-12-18 22:25

    Hello add corrections:

    var seeArea = L.GeometryUtil.geodesicArea(layer.getLatLngs()[0]); console.log(seeArea);

    0 讨论(0)
提交回复
热议问题