interface
ISwitchMapStyleParams
{
map
: mapboxgl.
Map
;
style
: string | mapboxgl.
Style
;
layersList
: string[];
sourcesList
: string[];
async
function
switchMapStyle
(
{
style,
sourcesList,
layersList,
}: ISwitchMapStyleParams
) {
let
newStyle;
if
(
typeof
style !==
"string"
) {
newStyle = style;
}
else
{
const
res =
await
axios.
get
(
`https://api.mapbox.com/styles/v1/
${style}
?access_token=
${mapboxgl.accessToken}
`
newStyle = res.
data
;
const
currentStyle = map.
getStyle
();
const
currentSources =
Object
.
keys
(currentStyle.
sources
).
reduce
(
(
obj, key
) =>
{
for
(
let
i =
0
; i < sourcesList.
length
; i++) {
const
sourcesKey = sourcesList[i];
if
(key.
startsWith
(sourcesKey)) {
obj[key] = currentStyle.
sources
[key];
break
;
return
obj;
newStyle.
sources
= { ...newStyle.
sources
, ...currentSources };
const
currentLayer = currentStyle.
layers
.
filter
(
(
e
) =>
{
for
(
let
i =
0
; i < layersList.
length
; i++) {
const
layersKey = layersList[i];
if
(e.
id
.
startsWith
(layersKey)) {
return
true
;
return
false
;
newStyle.
layers
= [...newStyle.
layers
, ...currentLayer];
map.
setStyle
(newStyle);
const styleUrl = 'https://zhejiang.tianditu.gov.cn/xxxxxxxxs_zw.json'
const res = await axios.get(styleUrl);
switchMapStyle({
map: this.map,
style: res.data,
sourcesList: ["mapbox-gl-draw-", "ml-"],
layersList: ["gl-draw-", "ml-layerInfo-"],
再解释下这里的 sourcesList 和 layersList
"mapbox-gl-draw-"和"gl-draw-"是用来保留"@mapbox/mapbox-gl-draw"这个插件绘图出来的图层的,你没有的话就不用加
“ml-”和"ml-layerInfo-"是该项目的所有手动添加的source和layer都有各自的专有前缀,这也是我们switchMapStyle方法里用来过滤的关键
【代码不规范,亲人两行泪,如果你的项目没有特别的专有前缀就去debugger看看currentStyle的内容吧...】
mapbox的issue【github】
mapbox地图自定义主题切换踩坑指南【掘金】