mapbox - 在 Mapbox 中,使用 setStyle 时如何保留图层?
问题描述
我为此奋斗了很久。挑战在于,我可能会在一种样式上绘制几个不同的图层,然后调用setStyle
(例如:转到卫星视图)来清除我所有的图层。
解决方案
我通过复制我关心的图层和资源并重新应用它们来解决它
function forEachLayer(text, cb) {
this.map.getStyle().layers.forEach((layer) => {
if (!layer.id.includes(text)) return;
cb(layer);
});
}
// Changing the map base style
export function changeStyle(style) {
const savedLayers = [];
const savedSources = {};
const layerGroups = [
'layer-type-1',
'layer-type-2'
];
layerGroups.forEach((layerGroup) => {
this.forEachLayer(layerGroup, (layer) => {
savedSources[layer.source] = this.map.getSource(layer.source).serialize();
savedLayers.push(layer);
});
});
this.map.setStyle(`mapbox://styles/mapbox/${style}`);
setTimeout(() => {
Object.entries(savedSources).forEach(([id, source]) => {
this.map.addSource(id, source);
});
savedLayers.forEach((layer) => {
this.map.addLayer(layer);
});
}, 1000);
}
推荐阅读
- c# - 在 Windows 上 Nugeting 一个多平台项目
- psychtoolbox - 等待特定时间单击鼠标右键或左键,然后继续
- google-app-engine - HTTP(S) 到特定资源的区域流量路由 - Google Cloud
- javascript - 如何在旋转的圆圈后面居中文本?
- python - 从自定义函数中保存 matplotlib
- php - 我如何在 php 中使用肥皂服务?
- python - Python - 用先前拆分的字符串替换给定目录中所有文件中的部分字符串
- c - TIM2 溢出不会触发 TIM2_IRQHandler @ STM32G031J6
- flutter - 过滤和排序 Firestore 数据颤动
- javascript - 角表行没有按预期跨越表?