mapBox中实现多图层绘画

如果可以实现记得点赞分享,谢谢老铁~

在开始之前,我们先看下效果图,如下:
在这里插入图片描述

第一步,写一个initDrawLayer 绘画图层的方法,这里面主要处理图层的闭合,生成,颜色,透明度等样式。这里主要用到了遍历,才可以生成多个图层。代码如下:

// 初始化加载图层
// ps: 这里的data 就是传入的经纬度的集合
  const initDrawLayer = (data: any) => {
    let allList: any = [];
    data?.forEach((item: any) => {
      if (item && item.coordinates && item.coordinates.length > 0) {
        // Add a data source containing GeoJSON data.
        const source = map.current.getSource('maine');

        const JsonObj: any = {
          'type': 'geojson',
          "data": {
            "type": "FeatureCollection",
            "features": [{
              "type": "Feature",
              "properties": { "name": "Null Island" },
              "geometry": {
                "type": "Polygon",
                "coordinates": [item.coordinates]
              }
            }]
          }
        }

        let jsonObjList = JsonObj.data.features[0].geometry.coordinates[0]
        // 这个地方主要判断经纬度结合中的首尾要闭合,要一样。
        if (
          jsonObjList[0][0] !== jsonObjList[jsonObjList.length - 1][0] &&
          jsonObjList[0][1] !== jsonObjList[jsonObjList.length - 1][1]
        ) {
          jsonObjList.push(item.coordinates[0])
        }
        if (source) {
          const featuresList = source._data.features;
          featuresList.push(JsonObj.data.features[0])
          source.setData({
            "type": "FeatureCollection",
            "features": featuresList
          })
        } else {
          map?.current?.addSource(`maine`, JsonObj);
        }
      }

    });
    // Add a new layer to visualize the polygon.
    map?.current?.addLayer({
      'id': `maine`,
      'type': 'fill',
      'source': 'maine', // reference the data source
      'layout': {},
      'paint': {
        'fill-color': '#0080ff', // blue color fill
        'fill-opacity': 0
      }
    });
    // Add a black outline around the polygon.
    map?.current?.addLayer({
      'id': `outline`,
      'type': 'line',
      'source': 'maine',
      'layout': {},
      'paint': {
        'line-color': '#0080ff',
        'line-width': 1
      }
    });
  }

第二步,然后再调用initDrawLayer()之前务必要将原有的source 清除。

// 绘画区域
const addPolygonOne = (data: any[]) => {
  if (!map.current) return;
  const source = map.current.getSource('maine');
  if (source) {
    map.current.removeLayer('maine')
    source.setData({
      "type": "FeatureCollection",
      "features": []
    })
    initDrawLayer(data)
  }
};

useEffect(()=>{
  // data为经纬度的集合
  addPolygonOne(data)
})

参考资料:

关于Mapbox GL JS图层的API

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

前端加油站

你遇到的坑将由我来踩

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值