33

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

2 回答 2

38

您可以使用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
        }
    });
});
于 2013-08-15T16:26:19.187 回答
29

使用时要非常小心instanceofLeaflet.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';
    }

};
于 2014-08-01T14:32:27.937 回答