How to edit an existing layer using leaflet?
Thanks to the help of @user1919 who pointed me to the solution proposed in Stackoverflow, I could edit the existing layer with the plugin Leaflet.draw without customizing it ( at least not it's code ).
The edits now are made on the onEachFeature
function in the L.geoJSON
call like this:
var selectedFeature = null;
function handleJson(data) {
geojsonlayer=L.geoJson(data, {
onEachFeature: function (feature, layer) {
group.addLayer(layer);
layer.on('click', function(e){
if(selectedFeature){
selectedFeature.editing.disable();
// and Here I'll add the code to store my edited polygon in the DB or whatever I want to do with it
}
selectedFeature = e.target;
e.target.editing.enable();
});
}
}).addTo(group);
}
and so there is no need to use the edits from the menu in Leaflet.draw control
Now to use the Leaflet.draw control I had to add to the drawnItems
, which is the editable layer defined in Leaflet.draw control, the feature which I selected. It looks like this :
drawnItems.addLayer(e.target);
and define drawnItems in the edit of the Leaflet.draw control like this :
var drawControl = new L.Control.Draw({
edit: {
featureGroup: drawnItems
}
});
If my understanding is correct, the root cause of the issue resides in the fact that the layers you want to make editable through Leaflet.draw plugin are nested within a Layer Group (e.g. if they are built through L.geoJSon()
factory, which outputs a Feature Group).
But Leaflet.draw does not like nested groups in the drawnItems
Feature Group, so you have to add only "non-group" layers.
In that case, you would just need to "flatten" your Layer Group (if any) and extract only single / non-group layers, so that you can now safely add them into drawnItems
.
var geoJsonGroup = L.geoJson(myGeoJSON);
addNonGroupLayers(geoJsonGroup, drawnItems);
// Would benefit from https://github.com/Leaflet/Leaflet/issues/4461
function addNonGroupLayers(sourceLayer, targetGroup) {
if (sourceLayer instanceof L.LayerGroup) {
sourceLayer.eachLayer(function (layer) {
addNonGroupLayers(layer, targetGroup);
});
} else {
targetGroup.addLayer(sourceLayer);
}
}
Updated JSFiddle: http://jsfiddle.net/suL12z93/4/
Note: as mentioned in the code, there is actually a thread at Leaflet issue #4461 about adding such a functionality to core Leaflet. I am sure Leaflet maintainers would be more than happy to receive a Pull Request to implement it! :-)