我正在使用https://github.com/Leaflet/Leaflet.draw插件,而我正在尝试检索已编辑图层的图层类型。
在draw:created
事件中,我有layer
和layerType
,但在draw:edited
上(保存所有修改时触发)我获得了已编辑的图层列表
draw:created 事件
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);
});
draw:edited 事件
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
});
});
答案 0 :(得分:33)
您可以使用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
}
});
});
答案 1 :(得分:21)
使用instanceof
时要非常小心。 Leaflet.draw
plugin使用标准Leaflet's L.Rectangle。 Leaflet的矩形延伸Polygon。多边形延伸Polyline。因此,某些形状可能会使用此方法给您带来意想不到的结果。
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';
}
};