setStyle设置底图样式移除所有图层问题
本来是想使用mapbox的卫星影像切片,通过addlayer方式添加,再通过.map.setLayoutProperty控制图层显示与隐藏来做到切换图层,但是在线影像切片放大到一定层级就没有了,而通过map.setStyle设置就不会发生这种问题,但是会移除所有图层,如原本底图上有的点线面等图层。拿到当前图层的所有样式进行拷贝与替换,再重新设置样式。
整体思路:
使用传入的map对象和styleID参数,构建一个GET请求的URL,其中包含了访问地图样式所需的访问令牌(access token)。以此获取指定样式(例如mapbox://styles/mapbox/streets-v11)的数据。
使用axios库发送GET请求,并使用解构赋值将返回的响应数据中的data字段赋值给newStyle变量。
获取当前地图样式的配置信息,保存在currentStyle变量中。
将当前样式中的所有数据源(sources)复制到新样式的数据源中,以确保保留了原有的数据源。
查找需要保留在新样式中的图层的索引位置。这里通过查找newStyle.layers数组中id为’waterway-label’的图层来确定插入位置。如果找不到该图层,则默认将新图层插入到最后。
从当前样式中筛选出需要保留的应用程序图层(app layers)。这些图层是那些具有不同数据源设置的图层。
构建新的图层数组,按照以下顺序排列:将0到labelIndex之间的图层拷贝到新数组中,然后将所有图层拷贝到新数组中,最后将labelIndex到倒数第二个图层拷贝到新数组中。
使用map.setStyle(newStyle)方法将地图样式设置为新样式。
相关实现代码函数
mapStyleSwitcher(data) {
axios
.get(
`https://api.mapbox.com/styles/v1/${data}?access_token=${token}`
)
.then((result) => {
const { data: newStyle } = result;
const currentStyle = map.getStyle();
newStyle.sources = Object.assign({}, currentStyle.sources,newStyle.sources);
let labelIndex = newStyle.layers.findIndex((el) => {
return el.id == "waterway-label";
});
if (labelIndex === -1) {
labelIndex = newStyle.layers.length;
}
const appLayers = currentStyle.layers.filter((el) => {
return el.source && el.source != "mapbox://mapbox.satellite" && el.source != "mapbox" && el.source != "composite";
});
newStyle.layers = [...newStyle.layers.slice(0,labelIndex),...appLayers,...newStyle.layers.slice(labelIndex, -1)];
map.setStyle(newStyle);
map.setStyle(newStyle);
})
.catch((error) => {
console.log(error);
});
},
方法调用
if (val === 2) {
this.mapStyleSwitcher("mapbox/satellite-v9");
} else {
this.mapStyleSwitcher("tracob/ckwg3ocos31nj14oqq2u3uq3n/draft");
}