6

With leaflet.js using leaflet.draw.js after using the draw tool to draw one of the shapes on a custom map. I have a form that pops up which says save or cancel. If the user presses cancel, then I want the drawing to be deleted. For example I was drawing a rectangle.

Here is my current source

map.on('draw:created', function(e) {
    var layer = e.layer;
    var type = e.layerType;

    $("#add-drawing").fadeIn(500);

    featureGroup.addLayer(e.layer); // Adds rectangle

    $("a.cancelD").on("click", function() {
        $("#add-drawing").fadeOut(500);

        // THESE ARE THE METHODS I HAVE TRIED TO REMOVE THE RECTANGLE
        map.removeLayer(layer);
        featureGroup.removeLayer(layer);
        map.removeLayer(e);
        featureGroup.removeLayer(e);
    });     
});

None of this seems to be working. I can use the toolbox to remove the layer, but then I won't have any information submitted in the form I wish to submit.

How can I remove objects that I have drawn when pressing the cancel button on a form?

4

3 回答 3

8

由于您要添加到featureGroup,您说它有效,因此您也应该从中删除featureGroup。调用featureGroup.removeLayer(e.layer)or featureGroup.removeLayer(layer)(因为layer持有对 的引用e.layer)应该可以工作。

这是关于 Plunker 的一个工作示例:http ://plnkr.co/edit/kPvYbH?p=preview

在我看来,唯一的结论可能是您的事件没有触发,或者您遇到了某种奇怪的范围问题,但可以轻松调试:

$("a.cancelD").on("click", function() {
    console.log('Click fired!'); // Seeing this in your console, event works
    console.log(featureGroup); // Should return featureGroup instance, scope ok
    console.log(e.layer); // Should return polygon instance, scope ok

    // If all of the above works, this should too
    featureGroup.removeLayer(e.layer);
});     
于 2015-03-03T00:57:20.767 回答
1

我有同样的问题。对我来说,以下解决方案有效,

featureGroup.clearLayers(e.layer);

希望这会对某人有所帮助

于 2017-08-14T14:49:29.247 回答
1

或者,您可以简单地调用.clearLayers()featureGroup创建的图层来保存所有图纸。

于 2021-04-30T08:18:03.750 回答