我有一个传单地图,设置为当用户单击按钮时根据类别更改样式。
实时地图:http://maneesha.github.io/test_map.html http://maneesha.github.io/test_map.html
源代码:https://github.com/maneesha/maneesha.github.io https://github.com/maneesha/maneesha.github.io
每种风格都有一个传说。
我的问题是,当单击另一个按钮(或再次单击该按钮)时,我无法让旧图例消失。因此,每次单击时,您都会在地图上看到一个新的图例。
Putting
map.removeControl(legend);
在点击功能不起作用并且
在 js 控制台中的结果是:
Uncaught TypeError: Cannot read property 'removeFrom' of undefined
有任何想法吗?
编辑:上面的存储库已更改。实时站点不再存在;源代码位于https://github.com/maneesha/leaflet_map_with_styles_and_legends https://github.com/maneesha/leaflet_map_with_styles_and_legends
您正在分配变量legend
在处理函数中click
事件于change-gender
。如果你这样做,legend
仅在该功能中可用。如果你声明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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)