思路一:
通过地图点击事件map.on('click', 'layerID', e=> {console.log(e.features)})
获取鼠标点击的矢量要素,然后依据该要素的geojson添加新的数据源和图层。
思路二:
通过地图点击事件获取鼠标点击的矢量要素,然后依据该要素内的特定属性字段,通过setPaintProperty
改变绘制的样式。
核心代码及注释:
layerID
是图层的IDfill-color
是面要素的填充颜色,如果要改的是线要素就是:"line-color"
["get", 'index']
指的是获取该要素属性里的index值- 当要素的index等于yourIndex的值时,将fill-color改为#ff0000,默认情况下颜色为#FFFF00
const yourIndex = 1
map.setPaintProperty('layerID', "fill-color", [
"case",
["==", ["get", 'index'], yourIndex],
'#ff0000',
'#FFFF00',
]);
思路三(官网示例):
鼠标指向要素修改其透明度实现高亮效果: Create a hover effect
来自编写日期(20221123)一年后的更新:
思路一补充:
上面的思路二和三在实际生产中都会有一些问题,所以这里对思路一进行补充:
- 创建一个高亮图层单例的类
- 每次触发高亮就更新一下这个高亮图层
下面是代码:
/*
* @Date: 2023-12-27 10:12:03
* @LastEditTime: 2023-12-27 10:38:41
* @FilePath: \satellite-mapbox\src\utils\map\layer\highLightLayer.js
* @Description: 图层 - 高亮图层单例
*/
import mapboxgl from 'mapbox-gl'
import { map } from '@/utils/map/createMapbox'
class HighlightLayer {
layerName = 'highlightLayer' // 图层名称
feature = null // 图层数据
constructor(feature) {
if (!HighlightLayer.instance) {
this.feature = feature
// 判断图层是否存在与绘制图层
map.addSource(this.layerName, {
type: 'geojson',
data: this.feature || {
"type": "FeatureCollection",
"features": []
}
})
map.addLayer({
type: 'line',
id: this.layerName,
source: this.layerName,
layout: {
'visibility': 'visible', // "visible", "none"
},
paint: {
'line-color': '#ff00ff',
'line-width': 5,
}
})
HighlightLayer.instance = this // 将this挂载到HighlightLayer这个类的instance属性上
}
return HighlightLayer.instance
}
// 获取实例
static getInstance() {
if (!HighlightLayer.instance) {
HighlightLayer.instance = new HighlightLayer();
}
return HighlightLayer.instance;
}
// 更新图层
updateLayer(feature) {
console.log('feature: ', feature);
this.feature = feature
if (map.getSource(this.layerName)) {
map.getSource(this.layerName).setData(feature)
} else {
map.addSource(this.layerName, {
type: 'geojson',
data: feature
})
map.addLayer(this.options)
}
}
// 移除图层
removeLayer() {
map.removeLayer(this.layerName)
map.removeSource(this.layerName)
}
}
export {
HighlightLayer
}
使用方式:
- 地图加载时声明实例
import { HighlightLayer } from '@/utils/highlightLayer.js' // 引入
map.on('style.load', () => {
new HighlightLayer(null)
});
- 在点击矢量的时候更新高亮图层
map.on('click', layerName, (e) => {
HighlightLayer.getInstance().updateLayer(e.features[0])
})