我是Mapbox和javascript的新手。我试图稍微修改一个Mapbox GL代码示例,找到here,它允许切换多个图层的开/关。
我有四层,我希望用户打开和关闭这些图层,但是当地图最初显示时,我只想要切换一个图层。我可以在页面加载时关闭其中三个图层(这里以一个为例):
map.addSource("gnat-4zdrvs", {
type: 'vector',
url: 'mapbox://jesselangdon.bbtex1ps'
});
map.addLayer({
"id": "gnat",
"type": "line",
"source": "gnat-4zdrvs",
"source-layer": "gnat-4zdrvs",
"minzoom": 8,
"filter": [
"==",
"$type",
"LineString"
],
"layout": {
"visibility": "none",
"line-cap": "round",
"line-join": "round"
},
"paint": {
"line-width": 2,
"line-color": {
"base": 1,
"type": "interval",
"property": "C_Sin",
"stops": [
[1,"hsl(189, 81%, 79%)"],
[1.02,"hsl(189, 91%, 65%)"],
[1.04, "hsl(189, 81%, 53%)"],
[1.06,"hsl(189, 83%, 43%)"],
[1.08,"hsl(189, 89%, 34%)"],
[1.1,"hsl(189, 90%, 28%)"],
[1.3,"hsl(189, 96%, 21%)"]
],
"default": "hsl(0, 0%, 50%)"
}
}
})
但是,我对Javascript的了解有限,无法弄清楚如何设置可点击链接的菜单,以便只有"visible"
图层处于切换为“开启”的状态。
以下是控制切换菜单的代码段:
var toggleableLayerIds = [ 'conductivity', 'confinement', 'gnat', 'solar' ];
for (var i = 0; i < toggleableLayerIds.length; i++) {
var id = toggleableLayerIds[i];
var link = document.createElement('a');
link.href = '#';
link.className = 'active';
link.textContent = id;
link.onclick = function (e) {
var clickedLayer = this.textContent;
e.preventDefault();
e.stopPropagation();
var visibility = map.getLayoutProperty(clickedLayer, 'visibility');
if (visibility === 'visible') {
map.setLayoutProperty(clickedLayer, 'visibility', 'none');
this.className = '';
} else {
this.className = 'active';
map.setLayoutProperty(clickedLayer, 'visibility', 'visible');
}
};
var layers = document.getElementById('menu');
layers.appendChild(link);
}
地图可见here。请注意,切换菜单中的所有四个图层都是蓝色(表示它们处于“开”位置,而实际上唯一的“on”图层是solar)。欢迎任何帮助,建议或批评......谢谢!
答案 0 :(得分:1)
您正在无条件地在创建时将类设置为活动,即使图层不可见,也始终使链接变为蓝色。尝试这样的事情。
if(map.getLayoutProperty(id, 'visibility') === 'visible')
{
link.className = 'active';
}
虽然这需要在onload函数内完成,否则属性将是未定义的。