Danimt
Danimt

Reputation: 1067

Leaflet.draw retrieve layer type on draw:edited event

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

Upvotes: 35

Views: 24104

Answers (2)

martynas
martynas

Reputation: 12300

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

};

Upvotes: 30

Pwnosaurus
Pwnosaurus

Reputation: 2170

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

Upvotes: 40

Related Questions