在单张地图上删除图例 [英] Remove legend on leaflet map
问题描述
我设置了一个传单地图,以在用户单击按钮时根据类别更改样式.
实时地图: 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
事件的处理函数中分配变量legend
.如果这样做,legend
将仅在该功能中可用.如果在单击处理程序之前声明var 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
这将:
var genderLegend;
document.getElementById('change-gender').addEventListener('click', function () {
genderLegend = L.control({'position': 'topright'}).addTo(map);
});
console.log(genderLegend) // returns the legend instance
I have a leaflet map set to change styles based on a category when a user clicks a button.
Live map: http://maneesha.github.io/test_map.html
Source code: https://github.com/maneesha/maneesha.github.io
There is a legend for each style. My problem is I can't get the old legend to disappear when another button is clicked (or that button is clicked again). So you'll see on the map each time you click, a new legend appears.
Putting
map.removeControl(legend);
in the click function does not work and results in this in the js console:
Uncaught TypeError: Cannot read property 'removeFrom' of undefined
Any ideas?
EDIT: Repos above have been changed. Live site no longer exists; source code is at https://github.com/maneesha/leaflet_map_with_styles_and_legends
You're assigning the variable legend
in the handler function of the click
event on change-gender
. If you do that, legend
will only be available in that function. If you declare var legend;
before the click handler and then in the click handler change: var legend = L.control({position: 'topright'});
to legend = L.control({position: 'topright'});
legend will be available in the global scope so you can reach it from every function within the global scope.
This won't work:
document.getElementById('change-gender').addEventListener('click', function () {
var genderLegend = L.control({'position': 'topright'}).addTo(map);
});
console.log(genderLegend) // returns undefined
This will:
var genderLegend;
document.getElementById('change-gender').addEventListener('click', function () {
genderLegend = L.control({'position': 'topright'}).addTo(map);
});
console.log(genderLegend) // returns the legend instance
这篇关于在单张地图上删除图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!