I'm using the https://github.com/Leaflet/Leaflet.draw plugin and I'm trying to retrieve the layer type of an edited layer.
On the draw:created
event, I have the layer
and layerType
, but on draw:edited
(triggered when saving all edits) I get a list of layers that were edited.
The draw:created event
map.on('draw:created', function (e) {
var type = e.layerType,
layer = e.layer;
if (type === 'marker') {
// Do marker specific actions
}
// Do whatever else you need to. (save to db, add to map etc)
map.addLayer(layer);
});
The draw:edited event
map.on('draw:edited', function (e) {
var layers = e.layers;
layers.eachLayer(function (layer) {
//do stuff, but I can't check which type I'm working with
// the layer parameter doesn't mention its type
});
});
You could use instanceof
(docs here).
map.on('draw:edited', function (e) {
var layers = e.layers;
layers.eachLayer(function (layer) {
if (layer instanceof L.Marker){
//Do marker specific actions here
}
});
});
Be very careful when using instanceof
. Leaflet.draw
plugin uses standard Leaflet's L.Rectangle. Leaflet's rectangle extends Polygon. Polygon extends Polyline. Therefore, some shapes might give you unexpected results using this method.
var drawnItems = new L.FeatureGroup();
map.addLayer(drawnItems);
... add layers to drawnItems ...
// Iterate through the layers
drawnItems.eachLayer(function(layer) {
if (layer instanceof L.Rectangle) {
console.log('im an instance of L rectangle');
}
if (layer instanceof L.Polygon) {
console.log('im an instance of L polygon');
}
if (layer instanceof L.Polyline) {
console.log('im an instance of L polyline');
}
});
var getShapeType = function(layer) {
if (layer instanceof L.Circle) {
return 'circle';
}
if (layer instanceof L.Marker) {
return 'marker';
}
if ((layer instanceof L.Polyline) && ! (layer instanceof L.Polygon)) {
return 'polyline';
}
if ((layer instanceof L.Polygon) && ! (layer instanceof L.Rectangle)) {
return 'polygon';
}
if (layer instanceof L.Rectangle) {
return 'rectangle';
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With