mapbox - 有效切换图层内的要素可见性
问题描述
目前,我正在制作城市内十种最常见树种的交互式地图。对于地图,我希望用户能够切换十个物种中每一个的可见性,以及“所有其他”物种的切换。
问题是我目前实现这一目标的方法非常臃肿,并且可以显着简化
目前我的方法是创建一系列复选框
<input type='checkbox' id='checkbox0'checked> Check0 </input> <div></div>
<input type='checkbox' id='checkbox1'checked> Check1 </input> <div></div>
<input type='checkbox' id='checkbox2'checked> Check2 </input> <div></div>
...
<input type='checkbox' id='checkbox11'checked> Check11 </input> <div></div>
为树添加图层并设置其中的特征:
map.addLayer({
id: 'wpgTrees',
type: 'circle',
source: {
type: 'vector',
url: 'url_Goes_Here'
},
'source-layer': 'source_Goes_Here',
'paint': {
'circle-radius': [
'interpolate', ['linear'], ['zoom'],
13, 2,
20, 4,
],
'circle-color':[
'match',
['get','Common_Nam'],
'green ash', treeColours[0], // Bright red
'American Elm', treeColours[1], // Orange
'Linden species', treeColours[2], // Blue
'Siberian Elm', treeColours[3], //Light red
'bur oak', treeColours[4], //Green, purple
'Manitoba maple, boxelder', treeColours[5],
'black Ash', treeColours[6], // pink
'Colorado blue spruce', treeColours[7], // light blue
'Poplar species', treeColours[8], //light green
'white spruce', treeColours[9], //light puruple
treeColours[10] //All Others
],
}
});
然后为每个复选框(0 到 10,11 层)使用 addEventListener 来使用 . 设置油漆属性。
checkbox0.addEventListener('click',function() {
if(treeBoolean[0] == true) {
treeOpacity[0]=0;
treeBoolean[0] = !treeBoolean[0];
} else {
treeOpacity[0]=1;
treeBoolean[0] = !treeBoolean[0];
};
map.setPaintProperty('wpgTrees','circle-opacity',[
'match',
['get','Common_Nam'],
'green ash', treeOpacity[0],
'American Elm', treeOpacity[1],
'Linden species', treeOpacity[2],
'Siberian Elm', treeOpacity[3],
'bur oak', treeOpacity[4],
'Manitoba maple, boxelder', treeOpacity[5],
'black Ash', treeOpacity[6],
'Colorado blue spruce', treeOpacity[7],
'Poplar species', treeOpacity[8],
'white spruce', treeOpacity[9],
1,
]);
})
这种方法的问题是我需要为所有 11 种类型的功能重复代码的 addEventListener 部分。必须有更好的方法来做到这一点,因为我目前的方法将非常“臃肿”。
感谢您的时间和帮助。
解决方案
在循环中添加复选框和处理程序会更有效。并且还在循环中构造不透明度的表达式。例如,如果类型列表如下所示:
var treesTypes = [
{
type: 'green ash',
color: '#ff0000',
visible: true
},
...
];
不透明度的表达式可以得到如下:
var opacity = ["match", ["get", "Common_Nam"]];
treesTypes.forEach(function(treeType) {
opacity.push(treeType.type);
opacity.push(treeType.visible ? 1 : 0)
});
opacity.push(1);
map.setPaintProperty('wpgTrees', 'circle-opacity', opacity);
推荐阅读
- javascript - Node Js:使用 WebWorker 调整图像大小
- php - 使用 foreach 时存储数组数据
- java - Java程序计算集合中的正值
- swift - Swift 中的 DFS 没有终止
- javascript - Laravel 和 VueJS - 在哪里\如何放置实例和组件
- python-3.x - Heroku 中状态从 up 变为 crashed
- azure-devops - Azure DevOps 在将构建升级到生产后回滚
- c++ - IN、OUT、INOUT 参数
- jquery - 无法从客户端脚本调用 api
- html - 带有golang的DataTable中的动态URL