I am used to working
with OL3 and I wanted to try using leaflet and see if it is as powerful as OL. I loaded a map with some data from a GeoServer WFS layer using this tutorial from Georepublic.
var group = new L.featureGroup().addTo(map);
var geojsonlayer;
function handleJson(data) {
// console.log(data);
geojsonlayer=L.geoJson(data, {
style: function (feature) {
return {
"weight": 2,
"opacity": 0.65
};
},
onEachFeature: function (feature, my_Layer) {
my_Layer.bindPopup("ID : "+feature.properties.id+"
Name : "+feature.properties.name);
}
}).addTo(group);
map.fitBounds(group.getBounds());
}
I wanted to add some editing and found the Leaflet.draw plugin I loaded it, and so far I can add a feature to the database ( knowing how painful it will be with WFS-T I used an AJAX call to a php script instead ). Here is how I call the draw control :
var drawnItems = new L.FeatureGroup();
map.addLayer(drawnItems);
var drawControl = new L.Control.Draw({
edit: {
featureGroup: drawnItems
}
});
map.on('draw:created', function (e) {
//Here I call the php script that stores the created feature in the DB
});
The problem is when I want to edit the existing features using the Leaflet.draw plugin, so I thought of changing the featureGroup
in edit
to group
like this :
var drawControl = new L.Control.Draw({
edit: {
featureGroup: group
}
});
but now I get this error:
Uncaught TypeError: Cannot read property 'enable' of undefined
I have done some research and found that I need to enable editing of the layer with this : layer.editing.enable();
the problem is where to add it so that when I click on the edit icon in the Leaflet.draw control I can edit my layer.
I kind of liked the Leaflet.draw plugin menu on the side, is it possible to solve my problem using this plugin or should I make my own editing menu?
Answer
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
}
});
No comments:
Post a Comment