Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Leaflet.draw retrieve layer type on draw:edited event

Tags:

leaflet

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
    });
});
like image 543
Daniel T Avatar asked Aug 02 '13 10:08

Daniel T


2 Answers

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
        }
    });
});
like image 81
Pwnosaurus Avatar answered Oct 11 '22 22:10

Pwnosaurus


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

};
like image 31
martynas Avatar answered Oct 11 '22 20:10

martynas