Mapbox添加图层,鼠标hover高亮并显示弹窗popup

该博客聚焦前端开发,介绍了一种多边形交互效果的实现。先添加fill图层填充多边形区域、line图层显示边框,监听鼠标mousemove和mouseleave事件,鼠标移入创建popup并修改图层样式,移出时还原,还给出了数据结构提示。

一、功能场景:

在这里插入图片描述
在这里插入图片描述

二、实现代码:

具体思路:

  1. 先添加一个fill图层填充多边形区域,line图层显示多边形边框。
  2. 监听鼠标mousemove和mouseleave事件。
  3. 鼠标移入的时候创建popup,修改fill图层的透明度和line图层的宽度,移出时还原。

提示:
data为包含图层信息和坐标的对象数据,其中geom为经纬度数组,结构为polygon或MultiPolygon。

代码如下:

  data() {
    return {
      data: [],
      popup: null,
    };
  },
methods: {
	renderLayer(){
	  	this.data.forEach((element, index) => {
        this.map.addLayer({
          id: `${element.id}Fill`,
          type: 'fill',
          source: {
            type: 'geojson',
            data: {
              type: 'FeatureCollection',
              features: [
                {
                  type: 'Feature',
                  geometry: element.geom
                }
              ]
            }
          },
          paint: {
            'fill-color': 'orange',
            'fill-opacity': 0.2
          }
        });
        this.map.addLayer({
          id: `${element.id}Line`,
          type: 'line',
          source: {
            type: 'geojson',
            data: {
              type: 'FeatureCollection',
              features: [
                {
                  type: 'Feature',
                  geometry: element.geom
                }
              ]
            }
          },
          paint: {
            'line-color': '#003',
            'line-width': 2,
            'line-opacity': 0.5
          }
        });
        this.map.on('mousemove', `${element.id}Fill`, e => {
          this.popup = this.createPopup(e, element);
          this.popup.addTo(this.map);
          this.map.setPaintProperty(`${element.id}Fill`, 'fill-opacity', 0.5);
          this.map.setPaintProperty(`${element.id}Line`, 'line-width', 4);
        });
        this.map.on('mouseleave', `${element.id}Fill`, () => {
          this.map.setPaintProperty(`${element.id}Fill`, 'fill-opacity', 0.2);
          this.map.setPaintProperty(`${element.id}Line`, 'line-width', 2);
          this.popup.remove();
        });
      });
	},
	
	// 创建popup
    createPopup(e, feature) {
      if (this.popup) {
        this.popup.remove();
      }
      // 取区域的颜色
      const bgc = this.map.getPaintProperty(`${feature.id}bigFill`, 'fill-color');
      let html = `<div class="title" style="background: ${bgc}" title="${feature.name}">${
        feature.name
      }</div>
      `;
      let popup = new mapboxgl.Popup({
        offset: 0,
        closeButton: false,
        className: 'popup'
      })
        .setLngLat([e.lngLat.lng, e.lngLat.lat])
        .setHTML(html);
      return popup;
    },
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值