mapbox-gl
多次绘制地图报错问题
初次点击控制台显示正常,第二次点击时控制台报Error,报错内容如下:
mapbox-gl.js:30 Error: Layer with id "test_map" already exists on this map
at i.addLayer (mapbox-gl.js:34:125707)
at r.addLayer (mapbox-gl.js:34:328187)
at drawHN (TestMap.vue?./node_modules/cache-loader/dist/cjs.js??ref--14-0!./node_modules/babel-loader/lib!./node_modules/ts-loader??ref--14-2!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader-v16/dist??ref--0-1:46:17)
at callWithErrorHandling (runtime-core.esm-bundler.js:276:22)
at callWithAsyncErrorHandling (runtime-core.esm-bundler.js:285:21)
at emit (runtime-core.esm-bundler.js:761:9)
at Proxy.handleClick (button.js:147:12)
at callWithErrorHandling (runtime-core.esm-bundler.js:276:22)
at callWithAsyncErrorHandling (runtime-core.esm-bundler.js:285:21)
at HTMLButtonElement.invoker (runtime-dom.esm-bundler.js:521:97)
猜测错误产生原因:mapbox-gl
绘制图层是都会有一个图层ID,多次点击时图层ID 没变,导致图层ID 重复。
验证猜测:荣国随机数产生图层ID,查看控制台是否还继续报错
验证结果:控制台无报错,猜测正确
解决问题:在绘制图层前,先判断图层是否绘制,如已绘制清除重新绘制。
代码如下:
const drawHN = () => {
if ((state.map as any).getLayer("test_map")) {
(state.map as any).removeLayer("test_map"); //清除图层
(state.map as any).removeSource("test_map"); //清除图层数据
}
(state.map as any).addLayer({
id: "test_map",
type: "fill",
source: {
type: "geojson",
data: HN
},
layout: {
},
paint: {
"fill-color": "#ff0000",
"fill-opacity": 0.8
},
maxzoom: 6
});
};
mapbox-gl
多次绘制地图报错问题
初次点击控制台显示正常,第二次点击时控制台报Error,报错内容如下:
mapbox-gl.js:30 Error: Layer with id "test_map" already exists on this map
at i.addLayer (mapbox-gl.js:34:125707)
at r.addLayer (mapbox-gl.js:34:328187)
at drawHN (TestMap.vue?./node_modules/cache-loader/dist/cjs.js??ref--14-0!./node_modules/babel-loader/lib!./node_modules/ts-loader??ref--14-2!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader-v16/dist??ref--0-1:46:17)
at callWithErrorHandling (runtime-core.esm-bundler.js:276:22)
at callWithAsyncErrorHandling (runtime-core.esm-bundler.js:285:21)
at emit (runtime-core.esm-bundler.js:761:9)
at Proxy.handleClick (button.js:147:12)
at callWithErrorHandling (runtime-core.esm-bundler.js:276:22)
at callWithAsyncErrorHandling (runtime-core.esm-bundler.js:285:21)
at HTMLButtonElement.invoker (runtime-dom.esm-bundler.js:521:97)
猜测错误产生原因:mapbox-gl
绘制图层是都会有一个图层ID,多次点击时图层ID 没变,导致图层ID 重复。
验证猜测:荣国随机数产生图层ID,查看控制台是否还继续报错
验证结果:控制台无报错,猜测正确
解决问题:在绘制图层前,先判断图层是否绘制,如已绘制清除重新绘制。
代码如下:
const drawHN = () => {
if ((state.map as any).getLayer("test_map")) {
(state.map as any).removeLayer("test_map"); //清除图层
(state.map as any).removeSource("test_map"); //清除图层数据
}
(state.map as any).addLayer({
id: "test_map",
type: "fill",
source: {
type: "geojson",
data: HN
},
layout: {
},
paint: {
"fill-color": "#ff0000",
"fill-opacity": 0.8
},
maxzoom: 6
});
};