Mapbox GL如何添加 / 删除 /高亮图层?

效果图展示

在这里插入图片描述

1.初始化地图

 initMap() {
      let vm = this;
      //获取图层数据
      let p = new Promise((resolve, reject) => {
        resolve([vm.getAreaData()]);
      })
      p.then(res => {
        Require(['Axios', 'PSRMap', 'ResourceQuery', 'SpatialAnalyst', 'Projection', 'CustomGraphics', 'Util', 'Measure', 'Diagram'], () => {
          vm.amap = window.amap = new WebGIS.Map();
          amap.init('mapGridBox', {
            style: WebGIS.Config.styles.base,
            center: [108.78997882442495, 23.83413245081408],
            zoom: 6 ,// WebGIS.Config.examples.zoom
            container: 'mapGridBox',
            controls: ['geolocate', 'navigation'],
            fullExtent: WebGIS.Config.examples.fullExtent
          }, () => {
            amap.on('load', () => {
              res[0].then(res=>{
                let rgbList = [];
                res.colorList.forEach(item => {
                  let strlist = item.split(',');
                  let rgbastr = `rgba(${strlist[0] + ',' + strlist[1] + ',' + strlist[2]},0.5)`;
                  rgbList.push(rgbastr)
                });
                this.layerIds = [];//初始化图层id集合
                this.sourceIds = [];//初始化数据源id集合
                //let num = 0;
                res.arrlast.forEach((ite, index) => {
                  //num+=1;
                  vm.drawArea(ite, rgbList[index],res.nameList[index],index)
                });
              });
              // 处理射线数据
              /*******开始*******/
              window.markerGroup = new WebGIS.MarkerGroup(amap);
              window.measure = new WebGIS.Measure(amap);

            });
            amap.on('zoomend',function (data) {
              console.log(amap.getZoom());
            })
          });
        });
      })
    },

2.添加图层

    drawArea(coordinates, color, name, index) {
      let that = this;
      let arr = [];
      coordinates[0].forEach(ite => {
        arr.push(new WebGIS.Projection.mercatorToWgs84(ite));
      });
      let arrlist = [];
      arrlist.push(arr);
      //添加数据源
      amap.addSource(
        name +'gridSource' + index,
        {
          'type': 'geojson',
          'data': {
            'type': 'Feature',
            'geometry': {
              'type': 'Polygon',
              'coordinates': arrlist
            }
          }
        }
      );
      that.sourceIds.push(name +'gridSource' + index);
      //多边形
      amap.addLayer({
        'id': name + 'fill' + index,
        'type': 'fill',
        'source':  name +'gridSource' + index, // reference the data source
        'layout': {
          'visibility': 'visible'
        },
        'maxZoom': 22,
        'minZoom': 6,
        'paint': {
          'fill-color': color, // blue color fill
          'fill-opacity': 0.8
        }
      });
      that.layerIds.push(name + 'fill' + index);
      //描边
      amap.addLayer({
        'id': name + 'line' + index,
        'type': 'line',
        'source': name +'gridSource' + index,
        'layout': {
          'visibility': 'visible'
        },
        'maxZoom': 22,
        'minZoom': 6,
        'paint': {
          'line-color': '#000',
          'line-width': 1
        }
      });
      that.layerIds.push(name + 'line' + index);
      //文字
      amap.addLayer({
        'id': name+'text'+ index,
        "type": "symbol",
        "source": name +'gridSource' + index,
        "layout": {
          'visibility': 'visible',
          "text-field": name,
          "text-size": 12
        },
        'maxZoom': 22,
        'minZoom': 6,
      });
      that.layerIds.push(name+'text'+ index);
      let hoveredStateId = null;
      //图层绑定click事件
      amap.on('click',name + 'fill' + index,function (e) {
        that.setAreaHigh(name + 'fill' + index,color);
        //显示左侧抽屉
        if (! that.showDrawer) {
          that.showDrawer = true;
          if (this.gridType === 1) {
            //行业分类列表全选
            setTimeout(() => {
              that.$refs.categoryInforComponent.checkAllSelect();
            },200)
          }
        }
      })
    },

3.高亮图层

    setAreaHigh(id,color){
      let that = this;
      let obj = {
        id: id,
        color: color,
        isActive: true
      };
      if (that.polygonColor.length === 0) {
        //当前图层没有高亮则设置高亮,并将信息保存在polygonColor中
        amap.pmap.setPaintProperty(id, "fill-color", "#ff0000");
        that.polygonColor.push(obj);
      } else {
        //再次点击高亮图层则取消高亮(反之则高亮)
        if (that.polygonColor[0].id === id && that.polygonColor[0].isActive) {
          amap.pmap.setPaintProperty(
            that.polygonColor[0].id,
            "fill-color",
            that.polygonColor[0].color
          );
          obj.isActive = false;
        } else if (that.polygonColor[0].id === id && !that.polygonColor[0].isActive) {
          amap.pmap.setPaintProperty(
            that.polygonColor[0].id,
            "fill-color",
            "#ff0000"
          );
          obj.isActive = true;
        } else if (that.polygonColor[0].id !== id) {
          //将之前高亮的图层改完本身的颜色
          amap.pmap.setPaintProperty(
            that.polygonColor[0].id,
            "fill-color",
            that.polygonColor[0].color
          );
          //然后将当前点击的图层高亮
          amap.pmap.setPaintProperty(
            id,
            "fill-color",
            "#ff0000"
          );
          obj.isActive = true;
        }
        //清空设置高亮集合
        that.polygonColor = [];
        //将当前高亮的图层信息保存在polygonColor中
        that.polygonColor.push(obj);
      }
    },

4.删除图层,并重新渲染图层

 async gridTypeChange(){
      //删除图层
      if (this.layerIds.length) {
        this.layerIds.forEach(id => {
          amap.removeLayer(id)
        })
        this.layerIds = [];
      }
      //删除数据源
      if (this.sourceIds.length) {
        this.sourceIds.forEach(id =>{
          amap.removeSource(id)
        })
        this.sourceIds = [];
      }
      //重新添加图层
      let res = await this.getAreaData();
      let rgbList = [];
      res.colorList.forEach(item => {
        let strlist = item.split(',');
        let rgbastr = `rgba(${strlist[0] + ',' + strlist[1] + ',' + strlist[2]},0.5)`;
        rgbList.push(rgbastr)
      });
      let num = 0;
      res.arrlast.forEach((ite, index) => {
        num += 1;
        this.drawArea(ite, rgbList[index],res.nameList[index],num)
      });
    }
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
以下是一个使用MapboxGL添加一个marker并实现高亮闪烁效果的完整代码示例: ```html <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>MapboxGL Marker Highlight Animation</title> <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" /> <script src="https://api.mapbox.com/mapbox-gl-js/v2.5.1/mapbox-gl.js"></script> <link href="https://api.mapbox.com/mapbox-gl-js/v2.5.1/mapbox-gl.css" rel="stylesheet" /> <style> body { margin: 0; padding: 0; } #map { position: absolute; top: 0; bottom: 0; width: 100%; } .highlight-animation { animation: highlight 1s infinite; } @keyframes highlight { 0% { opacity: 1; transform: scale(1); } 50% { opacity: 0.5; transform: scale(1.5); } 100% { opacity: 1; transform: scale(1); } } </style> </head> <body> <div id="map"></div> <script> mapboxgl.accessToken = 'YOUR_MAPBOX_ACCESS_TOKEN'; var lng = -122.4194; // 经度 var lat = 37.7749; // 纬度 var zoomLevel = 12; // 缩放级别 // 创建地图实例 var map = new mapboxgl.Map({ container: 'map', style: 'mapbox://styles/mapbox/streets-v11', center: [lng, lat], zoom: zoomLevel }); // 创建一个图层,并向地图添加一个marker var marker = new mapboxgl.Marker({ element: createMarkerElement() }) .setLngLat([lng, lat]) .addTo(map); // 为标记元素添加动画类 marker.getElement().classList.add('highlight-animation'); // 创建标记元素及样式 function createMarkerElement() { var el = document.createElement('div'); el.className = 'marker'; el.style.backgroundImage = 'url(https://example.com/your-marker-icon.png)'; // 替换为您自己的标记图标URL el.style.width = '40px'; el.style.height = '40px'; el.style.backgroundRepeat = 'no-repeat'; el.style.backgroundSize = 'cover'; return el; } </script> </body> </html> ``` 请确保将YOUR_MAPBOX_ACCESS_TOKEN替换为您自己的Mapbox访问令牌,并将`https://example.com/your-marker-icon.png`替换为您自己的标记图标的URL。 通过上述代码,您将能够在MapboxGL地图上添加一个marker,并为其添加高亮闪烁的动画效果。根据您的需求,您可以调整地图的样式、标记的位置和动画效果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值