問題描述
我正在使用leaflet.js 庫根據統計數據創建多個地圖.每個地圖顯示不同的值范圍,因此當用戶更改地圖時更改圖例會很好.
I`m using leaflet.js library to create multiple maps based on statistical data. Each map displays different range of values so it would be nice to change legend when user change map.
我在這個問題中找到了類似的例子,但我需要在兩個以上的層之間切換.我嘗試在代碼中簡單地添加更多if"語句和邏輯運算符,但它不能正常工作:
I found similar example in this question, but I need to switch between more than two layers. I try simply add more "if" statments and logical operators in code, but it doesn`t work right:
map.on('baselayerchange', function (eventLayer) {
if (eventLayer.name === 'Agricultural') {
map.removeControl(VODlegend || BUDlegend || LISlegend);
SGlegend.addTo(map);
}
else if (eventLayer.name === 'Building') {
map.removeControl(SGlegend || LISlegend || VODlegend);
BUDlegend.addTo(map);
}
else if (eventLayer.name === 'Forest') {
map.removeControl(BUDlegend || VODlegend || SGlegend);
LISlegend.addTo(map);
}
else if (eventLayer.name === 'Water') {
map.removeControl(LISlegend || SGlegend || BUDlegend);
VODlegend.addTo(map);
}
})
這是我在 jsfiddle 上的地圖示例.如果有任何幫助,我將不勝感激.
Here is example of my map on jsfiddle. I would be grateful for any help.
推薦答案
視頻傳奇 ||BUD傳奇 ||LIS傳奇
VODlegend || BUDlegend || LISlegend
在 javascript 中,這是一個條件(結果為真或假)...不是您期望的列表
In javascript, this is a condition (result is true or false) ... not a list as you expect
你需要像這樣跟蹤你當前的控件
You need to keep track of your current control like that
SGlegend.addTo(map);
currentLegend = SGlegend;
map.on('baselayerchange', function (eventLayer) {
if (eventLayer.name === 'Agricultural') {
map.removeControl(currentLegend );
currentLegend = SGlegend;
SGlegend.addTo(map);
}
else if (eventLayer.name === 'Building') {
map.removeControl(currentLegend );
currentLegend = BUDlegend;
BUDlegend.addTo(map);
}
else if (eventLayer.name === 'Forest') {
map.removeControl(currentLegend );
currentLegend = LISlegend;
LISlegend.addTo(map);
}
else if (eventLayer.name === 'Water') {
map.removeControl(currentLegend );
currentLegend = VODlegend;
VODlegend.addTo(map);
}
})
修改后的小提琴在這里:http://jsfiddle.net/FranceImage/X678g/
Modified fiddle is here: http://jsfiddle.net/FranceImage/X678g/
這篇關于如何使用leaflet.js 在多個地圖圖例之間切換?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!