Update Turf JS area in Leaflet popup using Geoman "edit layers"

431 Views Asked by At

I have a QGIS project that I exported to a web map using QGIS2WEB. Using Turf JS, I have a popup that displays the area of each polygon in my web map. Using Geoman, I would like to be able to edit the polygons in the web map and have the area calculation automatically update in the leaflet popup. I was able to get this working with "cut layers" but not with "edit layers". Here is a piece of my code below

var layer_TestLandscapeArea_1 = new L.geoJson(json_TestLandscapeArea_1, {
            attribution: '',
            interactive: true,
            dataVar: 'json_TestLandscapeArea_1',
            layerName: 'layer_TestLandscapeArea_1',
            pane: 'pane_TestLandscapeArea_1',
            style: style_TestLandscapeArea_1_0,
            onEachFeature: function (feature, layer) {
            area = (turf.area(feature)).toFixed(2);
            center_lat = turf.center(feature).geometry.coordinates[1]
            center_long = turf.center(feature).geometry.coordinates[0]
            bbox = turf.bbox(feature).toString();
            layer.bindPopup(`<b>Area: </b> ${area} </br> <b>Center(x,y): </b> (${center_long, center_lat}) </br> <b>Bbox: </b> [${bbox}]`)
        }
        });
        bounds_group.addLayer(layer_TestLandscapeArea_1);
        map.addLayer(layer_TestLandscapeArea_1);
        setBounds();
            
            
        // add Leaflet-Geoman controls with some options to the map  
        map.pm.addControls({  
        position: 'topleft',  
        drawCircle: false,  
        });  
1

There are 1 best solutions below

0
On

You can listen on the pm:edit event and then make your calculations again.

var layer_TestLandscapeArea_1 = new L.geoJson(json_TestLandscapeArea_1, {
            attribution: '',
            interactive: true,
            dataVar: 'json_TestLandscapeArea_1',
            layerName: 'layer_TestLandscapeArea_1',
            pane: 'pane_TestLandscapeArea_1',
            style: style_TestLandscapeArea_1_0,
            onEachFeature: function (feature, layer) {
                calc(layer);
                layer.on('pm:edit',function(e){
                   calc(e.layer);
                });
            }
});


function calc(layer){
   var feature = layer.feature;
   area = (turf.area(feature)).toFixed(2);
   center_lat = turf.center(feature).geometry.coordinates[1]
   center_long = turf.center(feature).geometry.coordinates[0]
   bbox = turf.bbox(feature).toString();
   layer.bindPopup(`<b>Area: </b> ${area} </br> <b>Center(x,y): </b> (${center_long, center_lat}) </br> <b>Bbox: </b> [${bbox}]`)
}