Leaflet删除先前的折线。

3

我有一个在点击事件上重新创建折线的函数。它能够正常工作,但是刷新层仍然保留着以前的折线。只有当我缩放地图时,以前的折线才会消失。

我的代码:

function buildHotline(response) {
    //clearMap();
    //clear_polyline();
    document.getElementById('mapid').innerHTML = "<div id='map' style='width: 100%; height: 100%;'></div>";
    //document.getElementById('map').innerHTML = "<div id='mapid' style='width: 100%; height: 100%;'></div>";
    var tiles = L.tileLayer('http://{s}.tile.openstreetmap.se/hydda/full/{z}/{x}/{y}.png', {
    attribution: 'Tiles courtesy of <a href="http://openstreetmap.se/" target="_blank">OpenStreetMap Sweden</a> &mdash; Map data &copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'});


    var map = new L.map('map', {
        layers: [tiles],
        scrollWheelZoom: true,
        dragging: true,
        tap: false
    });


    var hotlineLayer = L.hotline(response, {
        min: 0,
        max: 120,
        palette: {
            0.0: '#3ebcef',
            0.5: '#78b3d3',
            1.0: '#000203'
        },
        weight: 5,
        outlineColor: '#000203',
        outlineWidth: 1
    });



    //clear first
    clear_polyline();

    bounds = hotlineLayer.getBounds();
    map.fitBounds(bounds);



    hotlineLayer.addTo(map);


    function clear_polyline() {
        try {
            // statements
            setTimeout(function(){ map.invalidateSize()}, 400);
            //alert("erase line");
            map.removeLayer( hotlineLayer );

        } catch(e) {
            // statements
            console.log(e);
        }

    }

}

在创建新的折线之前,我需要将clear_polyline放在哪里以先清除它。谢谢。

1个回答

0
将对 hotlineLayer 的引用放在 buildHotline() 函数的作用域之外,以便该函数的多次运行可以引用同一个 hotlineLayer 实例。
然后,检查它是否未定义,如果不是,则删除它,并使用新构建的实例重新分配。

i.e.:

var thing;

function refreshThing() {
    if (thing) { remove(thing); }
    thing = newThing();
}

另请参阅如何删除L.rectangle(boxes[i]),因为解决方案非常相似。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接