Leaflet.draw retrieve layer type on draw:edited event

不羁的心 提交于 2019-12-18 10:44:09

问题


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
    });
});

回答1:


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
        }
    });
});



回答2:


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');
    }

});

How do i find out the shape type?

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';
    }

};


来源:https://stackoverflow.com/questions/18014907/leaflet-draw-retrieve-layer-type-on-drawedited-event

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!