【WebGIS实例】(3)MapboxGL实现矢量要素点击高亮

思路一:

通过地图点击事件map.on('click', 'layerID', e=> {console.log(e.features)})获取鼠标点击的矢量要素,然后依据该要素的geojson添加新的数据源和图层。

思路二:

通过地图点击事件获取鼠标点击的矢量要素,然后依据该要素内的特定属性字段,通过setPaintProperty改变绘制的样式。

核心代码及注释

  • layerID是图层的ID
  • fill-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)一年后的更新:

思路一补充:

上面的思路二和三在实际生产中都会有一些问题,所以这里对思路一进行补充:

  1. 创建一个高亮图层单例的类
  2. 每次触发高亮就更新一下这个高亮图层

下面是代码

/*
 * @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
}

使用方式

  1. 地图加载时声明实例
import { HighlightLayer } from '@/utils/highlightLayer.js' // 引入

map.on('style.load', () => {
  new HighlightLayer(null)
});
  1. 在点击矢量的时候更新高亮图层
map.on('click', layerName, (e) => {
  HighlightLayer.getInstance().updateLayer(e.features[0])
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值