踩坑指南
首先要明白切换底图其实就是切换的创建示例时候的style,就是这个玩意儿
我这里称他为map.json文件
map.json里面包括了底图的图源source以及渲染时所需的layer(层)
成功渲染需要layer和source配合,其中source提供的是数据,layer提供的是具体的渲染条件
这里粘一个完整的map.json
{
"version": 8,
"name": "Streets",
"metadata": {
"maputnik:renderer": "mbgljs"
},
"center": [
0,
0
],
"zoom": 1,
"bearing": 0,
"pitch": 0,
"sources": {
"satellite0-9": {
"type": "raster",
"url": "http://localhost/satellite0-9.json"
},
"desert_1": {
"type": "raster",
"url": "http://localhost/desert_1.json"
},
"desert_2": {
"type": "raster",
"url": "http://localhost/desert_2.json"
},
"desert_3": {
"type": "raster",
"url": "http://localhost/desert_3.json"
},
"desert_4": {
"type": "raster",
"url": "http://localhost/desert_4.json"
},
"places": {
"type": "geojson",
"data": {
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"properties": {},
"geometry": {
"type": "LineString",
"coordinates": []
}
}]
},
"animate": true
},
"points": {
"type": "geojson",
"data": {
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"properties": {},
"geometry": {
"type": "LineString",
"coordinates": []
}
}]
}
}
},
"sprite": "http://localhost:8848/icon/sprite",
"glyphs": "http://localhost/NotoSans-hinted/{fontstack}/{range}.pbf",
"layers": [{
"id": "background",
"type": "background",
"layout": {
"visibility": "visible"
},
"paint": {
"background-color": "rgba(149, 185, 206, 1)"
}
}, {
"id": "satellite0-9",
"type": "raster",
"source": "satellite0-9",
"minzoom": 0,
"maxzoom": 24,
"layout": {
"visibility": "visible"
}
}, {
"id": "desert_1",
"type": "raster",
"source": "desert_1",
"minzoom": 10,
"maxzoom": 24
}, {
"id": "desert_4",
"type": "raster",
"source": "desert_4",
"minzoom": 10,
"maxzoom": 24
}, {
"id": "desert_3",
"type": "raster",
"source": "desert_3",
"minzoom": 10,
"maxzoom": 24
}, {
"id": "desert_2",
"type": "raster",
"source": "desert_2",
"minzoom": 10,
"maxzoom": 24
}],
"id": "streets"
}
按照我之前的思路 ,通过setStyle方法切换map.json之后,地图实例不会改变,之前在代码内部添加的layer也还能用
但是实际情况是,切换完了之后,数据就无法继续渲染了,
为此我打印了更改前后的map实例
切换前:
切换后:
切换完map.json之后,整个实例就已经变了,之前添加的source和layer都不存在,需要重新添加;
我就是这里没想明白才会踩坑;
因此,在切换完map.json之后,需要将自己用到的source和layer重新添加一遍
有两种思路:
1,直接将source和layer放到map.json中
2,setStyle完了之后重新添加source和layer
由于用到的layer较多,我又将其封装了起来,
所以我的做法是将source放到map.json中,然后切换map.json之后再掉一次添加layer的方法
需要特别注意的是,重新添加layer需要监听style.load事件 如果使用load事件依然无法渲染
this.map.on("style.load", function () {
//重新添加layer
layerAdd(that.map);
});
就可以成功解决问题
补充,我监听"style.load"事件时,发现在切换矢量地图和电子地图时会出现问题,切换完之后监听不到该事件,所以我又换成了监听 "styledata"事件,目前运行起来没什么问题,但是不知道什么原因会报一行错误
这个错误我还不清楚原因,但是现在看起来并不影响代码执行, 解决后会再来更新