成果图
实现方法
这里借鉴了官网这个例子
https://docs.mapbox.com/mapbox-gl-js/example/hover-styles/
这里是图层的样式配置,通过改变select的true和false,来控制渲染的颜色和宽度
paint: {'line-opacity': 1,'line-color': ['case',['boolean', ['feature-state', 'select'], false],'rgb(0,255,255)',['get','color']],// 'line-width':["match",["get","级别"],0,3.5,2],'line-width':['case',['boolean', ['feature-state', 'select'], false],4,2],},
选中的颜色select设置为true
map.on('mousemove','riverDanger',(e) =>{if (e.features.length > 0) {if (this.heighLight !== null) {map.setFeatureState({ source: 'riverDanger', id: this.heighLight },{ select: false });}this.heighLight = e.features[0].id;map.setFeatureState({ source: 'riverDanger', id: this.heighLight },{ select: true });}})map.on('mouseleave', 'riverDanger', () => {if (this.heighLight !== null) {map.setFeatureState({ source: 'riverDanger', id: this.heighLight },{ select: false });}this.heighLight = null;});
注意这里可能会出现找不到id的情况,那就手动给每一个要素添加ID,比如可以把index给id
geojsonData.features.forEach((e,index)=>{e.id = index})