删除传单地图上的图例

man*_*sha 5 javascript gis leaflet

我有一个传单地图,设置为当用户单击按钮时根据类别更改样式。

实时地图: http: //maneesha.github.io/test_map.html

源代码: https: //github.com/maneesha/maneesha.github.io

每种风格都有一个传说。我的问题是,当单击另一个按钮(或再次单击该按钮)时,我无法让旧图例消失。因此,每次单击时,您都会在地图上看到一个新的图例。

推杆

map.removeControl(legend);
Run Code Online (Sandbox Code Playgroud)

在单击功能中不起作用,并在 js 控制台中产生以下结果:

Uncaught TypeError: Cannot read property 'removeFrom' of undefined
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

编辑:上面的存储库已更改。实时站点不再存在;源代码位于https://github.com/maneesha/leaflet_map_with_styles_and_legends

iH8*_*iH8 2

您正在 事件legend的处理函数中分配变量。如果您这样做,则仅在该功能中可用。如果您在单击处理程序之前声明,然后在单击处理程序中进行更改:图例将在全局范围内可用,因此您可以从全局范围内的每个函数访问它。clickchange-genderlegendvar legend;var legend = L.control({position: 'topright'});legend = L.control({position: 'topright'});

这是行不通的:

document.getElementById('change-gender').addEventListener('click', function () {
    var genderLegend = L.control({'position': 'topright'}).addTo(map);
});

console.log(genderLegend) // returns undefined
Run Code Online (Sandbox Code Playgroud)

这会:

var genderLegend;

document.getElementById('change-gender').addEventListener('click', function () {
    genderLegend = L.control({'position': 'topright'}).addTo(map);
});

console.log(genderLegend) // returns the legend instance
Run Code Online (Sandbox Code Playgroud)