源代码: 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 instanceI 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.htmlSource code: https://github.com/maneesha/maneesha.github.ioThere 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.Puttingmap.removeControl(legend);in the click function does not work andresults in this in the js console:Uncaught TypeError: Cannot read property 'removeFrom' of undefinedAny 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 undefinedThis will:var genderLegend;document.getElementById('change-gender').addEventListener('click', function () { genderLegend = L.control({'position': 'topright'}).addTo(map);});console.log(genderLegend) // returns the legend instance 这篇关于在单张地图上删除图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 09-09 19:18