Leaflet.draw 在 draw:edited 事件中检索图层类型

34
我正在使用https://github.com/Leaflet/Leaflet.draw插件,并尝试检索编辑图层的图层类型。在draw:created事件中,我有layerlayerType,但在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
    });
});
2个回答

40

你可以使用instanceof (这里是文档)

map.on('draw:edited', function (e) {
    var layers = e.layers;
    layers.eachLayer(function (layer) {
        if (layer instanceof L.Marker){
            //Do marker specific actions here
        }
    });
});

30

在使用 instanceof 时要非常小心。 Leaflet.draw 插件 使用标准的Leaflet L.Rectangle。Leaflet 的矩形扩展了Polygon。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';
    }

};

4
更好的做法难道不是反转顺序吗?测试矩形-->返回,测试多边形-->返回,测试折线-->返回。 - Don
1
谢谢伙计!!我卡住了,不知道为什么我的折线被识别成了多边形..现在我明白了!谢谢!!!!!! - Gangai Johann

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接