我使用 Mapbox tutorial 创建了一个多等值线图,并希望根据当前数据层的内容切换图例。
这是我试图用来更改图例的函数:
function changeLegend() {
var previousLegend = $('.map-legends').html()
map.legendControl.removeLegend(previousLegend)
map.legendControl.addLegend(getLegendHTML());
}
但它并没有正确删除图例,只是将它们叠加在一起。当我使用 jQuery 而不是 map.legendControl.removeLegend
删除图例时,先前的图例被删除,但是当我随后调用 map.legendControl.addLegend
时,它添加了 2 个图例即使生成图例 html 的函数只被点击一次。
有人可以帮我正确删除和添加图例吗?
最佳答案
在我检查了如何 L.mapbox.legendControl
之后工作我想我可能有你的问题的原因,让我首先解释一下它是如何工作的
-
map.legendControl._legends
是一个将图例保存为键的对象,值是通过map.legendControl.addLegend
添加的相等字符串的数量, 同样map.legendControl.removeLegend
减少给定键的值(如果存在)
例如
// at this point:
// map.legendControl._legends = {}
map.legendControl.addLegend('<span>hello world</span>')
// at this point:
// map.legendControl._legends = {
// '<span>hello world</span>': 1
// }
map.legendControl.addLegend('random string')
// at this point:
// map.legendControl._legends = {
// '<span>hello world</span>': 1,
// 'random string': 1
// }
map.legendControl.addLegend('random string')
// at this point:
// map.legendControl._legends = {
// '<span>hello world</span>': 1,
// 'random string': 2
// }
map.legendControl.removeLegend('random string')
// at this point:
// map.legendControl._legends = {
// '<span>hello world</span>': 1,
// 'random string': 1
// }
现在我们知道它是如何保存它们的,让我们看看它是如何呈现它们的(每次您通过其 addLegend
方法 removeLegend
或 _update
时都会自动完成此操作
- 它迭代
_legend
对象,对于找到的每个键,它将用<div class="map-legend wax-legend"></div>
包装元素并每个键渲染一次(它实际上使用_legend[some key]
作为一个简单的计数器,它不使用它来渲染东西)
重要提示:如果 key 中有 html,它将首先被清除
上面的例子将呈现为
<div class="map-legend wax-legend"><span>hello world</span></div>
<div class="map-legend wax-legend">random string</div>
这是 .map-legends
的内容容器
<div class="map-legends wax-legends leaflet-control">
<div class="map-legend wax-legend"><span>hello world</span></div>
<div class="map-legend wax-legend">random string</div>
</div>
回到你正在做的代码var previousLegend = $('.map-legends').html()
如上所示,它将返回您的传说包裹在里面 <div class="map-legend">
而且它们不会被删除
一个简单的解决方案是避免使用 $('.map-legends').html()
获取先前插入的 html,而不是将其保存在这样的变量中
var previousLegend;
function changeLegend() {
if (previousLegend) map.legendControl.removeLegend(previousLegend)
var newLegend = getLegendHTML();
map.legendControl.addLegend(newLegend);
previousLegend = newLegend;
}
关于javascript - 如何使用 Mapbox 更改多个等值线图中的图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36853073/