Search code examples
javascriptleafletleaflet-geoman

Leaflet-geoman how to properly retrieve GeoJSON


I'm having some troubles when it comes to using the draw control given by leaflet-geoman:

What I'm trying to achieve:

  • Draw Polygon(s) --> ✅
  • Get geojson from layer(s) --> ✅
  • Store in database --> ✅
  • Retrieve from database --> ✅
  • Load in leaflet map and be able to edit, crop it and remove it. --> ✅ ?
  • Get new geojson from modified layer(s) or if I had 2 layers and removed one, get only one. --> X

I haven't been able to get the new geojson from the modifications I did through the geoman draw control. No matter what I do, I always get the same result I had in the beginning when I loaded the data to the map.

Fiddle: https://jsfiddle.net/pjkLr41q/34/

const shapes = [{
          "type": "Feature",
          "properties": {},
          "geometry": {
            "type": "Polygon",
            "coordinates": [
              [
                [-3.701856, 40.422481],
                [-3.707092, 40.418593],
                [-3.70177, 40.417809],
                [-3.701899, 40.422873],
                [-3.701856, 40.422481]
              ]
            ]
          }
        }];
const geojson = L.geoJSON(shapes).addTo(map);


map.eachLayer((layer) => {
 if (layer.pm) {
   const geojson = layer.toGeoJSON();

   if (layer instanceof L.Circle) {
     geojson.properties.radius = 10;
   }

   shapes.push(geojson);
}});

I ain't sure if its because the way I load the data, straight with the L.geoJSON(data) or maybe going through the eachLayer function isn't what I need in this case, but I'm kinda lost right now. Help really appreciated.


Solution

  • You can get all Geoman layers with: L.PM.Utils.findLayers(map).

    In the next Version 2.7.0 there will be the functions map.pm.getGeomanLayers() and map.pm.getGeomanDrawLayers()

    So you can get the new geojson with:

    var layers = L.PM.Utils.findLayers(map);
    var group = L.featureGroup();
    layers.forEach((layer)=>{
        group.addLayer(layer);
    });
    shapes = group.toGeoJSON();