Leaflet.draw retrieve layer type on draw:edited event

后端 未结 2 1291
南方客
南方客 2020-12-24 12:22

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,

相关标签:
2条回答
  • 2020-12-24 12:25

    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
            }
        });
    });
    
    0 讨论(0)
  • 2020-12-24 12:42

    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';
        }
    
    };
    
    0 讨论(0)
提交回复
热议问题