今天實(shí)現(xiàn)了一個(gè)圖片切換的功能,圖片可以在mapbox上做切換顯示,然后再在相應(yīng)的圖片上做區(qū)域標(biāo)繪。但遇到一個(gè)問題,就是每次切換圖片都會擋住之前繪制的元素。
因?yàn)槲沂敲看吻袚Q都刪除了圖層重建,所以會導(dǎo)致這種現(xiàn)象發(fā)生。
// 移除舊圖層
if (this.currentImageLayer) {
if (this.map.getLayer(this.currentImageLayer)) {
this.map.removeLayer(this.currentImageLayer);
}
if (this.map.getSource(this.currentImageLayer)) {
this.map.removeSource(this.currentImageLayer);
}
}
const bbox = image.bbox;
const tileUrl = image.tileUrl;
const layerId = `roi-layer-${image.id}`;
this.currentImageLayer = layerId;
// 添加 source
this.map.addSource(layerId, {
type: 'image',
url: tileUrl,
coordinates: [
[bbox[0], bbox[3]],
[bbox[2], bbox[3]],
[bbox[2], bbox[1]],
[bbox[0], bbox[1]],
],
});
// 添加影像圖層,確保在所有 draw 圖層之下
this.map.addLayer({
id: layerId,
type: 'raster',
source: layerId,
paint: {
'raster-opacity': 0.9,
},
}); // 插入到最上層的 draw 圖層之前
// 調(diào)整視角
const centerLng = (bbox[0] + bbox[2]) / 2;
const centerLat = (bbox[1] + bbox[3]) / 2;
this.map.jumpTo({
center: [centerLng, centerLat],
zoom: 16,
});
查了好久資料,最靠譜的辦法是這樣的:
// 強(qiáng)制將所有 draw 圖層移到最頂層
const drawLayers = this.map
.getStyle()
.layers.filter((l) => l.id.startsWith('gl-draw-'))
.map((l) => l.id)
.reverse();
drawLayers.forEach((id) => {
if (this.map.getLayer(id)) {
this.map.moveLayer(id);
}
});
以下是全部代碼:
previewImage(image) {
this.selectedImage = image;
this.selectedImageId = this.selectedImage.id;
// 移除舊圖層
if (this.currentImageLayer) {
if (this.map.getLayer(this.currentImageLayer)) {
this.map.removeLayer(this.currentImageLayer);
}
if (this.map.getSource(this.currentImageLayer)) {
this.map.removeSource(this.currentImageLayer);
}
}
const bbox = image.bbox;
const tileUrl = image.tileUrl;
const layerId = `roi-layer-${image.id}`;
this.currentImageLayer = layerId;
// 添加 source
this.map.addSource(layerId, {
type: 'image',
url: tileUrl,
coordinates: [
[bbox[0], bbox[3]],
[bbox[2], bbox[3]],
[bbox[2], bbox[1]],
[bbox[0], bbox[1]],
],
});
// 添加影像圖層,確保在所有 draw 圖層之下
this.map.addLayer({
id: layerId,
type: 'raster',
source: layerId,
paint: {
'raster-opacity': 0.9,
},
}); // 插入到最上層的 draw 圖層之前
// 調(diào)整視角
const centerLng = (bbox[0] + bbox[2]) / 2;
const centerLat = (bbox[1] + bbox[3]) / 2;
this.map.jumpTo({
center: [centerLng, centerLat],
zoom: 16,
});
// 強(qiáng)制將所有 draw 圖層移到最頂層
const drawLayers = this.map
.getStyle()
.layers.filter((l) => l.id.startsWith('gl-draw-'))
.map((l) => l.id)
.reverse();
drawLayers.forEach((id) => {
if (this.map.getLayer(id)) {
this.map.moveLayer(id);
}
});
}