javascript – 删除传单地图上的图例

我有一个传单地图集,用于在用户单击按钮时根据类别更改样式.

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

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

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

map.removeControl(legend);

在单击功能中不起作用
在js控制台中产生这个结果:

Uncaught TypeError: Cannot read property 'removeFrom' of undefined

有任何想法吗?

编辑:上面的回购已被更改.现场不再存在;源代码是https://github.com/maneesha/leaflet_map_with_styles_and_legends

最佳答案 您在change-gender上的click事件的处理函数中分配变量图例.如果您这样做,图例将仅在该功能中可用.如果你声明var legend;在单击处理程序之前然后在单击处理程序中更改:var legend = L.control({position:’topright’}); to 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

这将:

var genderLegend;

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

console.log(genderLegend) // returns the legend instance
点赞