Mapbox GL实现在底图上动态叠加矢量瓦片

0 阅读1分钟

上篇写到了直接加载矢量瓦片图层比较简单,这篇实现存在底图,只在上面叠加矢量瓦片服务,或着实现底图切换功能。


<template>

  <div id="map" class="s-map-panel" ></div>

</template>
<script setup lang="ts">

import {onMounted} from "vue";
import {countryTdtServer} from "@/utils/tdtServer.ts";
import axios from "axios";
const {mapboxgl} = window as any
let map: any = null
const emits = defineEmits(['onMapLoaded']);

const initMap= ()=>{

  map=new mapboxgl.Map({
    container: 'map',
    style:countryTdtServer(),
    center: [108.95622, 34.279541],
    zoom: 12,
  });
  map.on('load', async () => {
    const vectorStyleUrl= 'https://shaanxi.tianditu.gov.cn/ServiceSystem/Tile/rest/service/sxww2022Geo/IbQuA4mA4-scWA4s/VectorTileServer/styles/default.json'
    const vecRes=await axios.get(vectorStyleUrl)
    try {

      if(vecRes.data){
      
        // 添加数据源
        Object.keys(vecRes.data.sources).forEach((sourceId) => {
          const prefixedSourceId = getUniqueId('btServer', sourceId);
          if (!map.getSource(prefixedSourceId)) {
            map.addSource(prefixedSourceId, vecRes.data.sources[sourceId]);
          }
        });

        if (vecRes.data.layers) {
          vecRes.data.layers.forEach((layer: any) => {
            layer.id = getUniqueId('btServer',  layer.id);
            if (!map.getLayer(layer.id)) {
              map.addLayer({
                ...layer,
                source: getUniqueId('btServer',  layer.source)
              });
            }
          });
        }


      }

    } catch (error) {
      console.error(error)
    }



  });

}


const getUniqueId=(customPrefix: string,  id: string): string => {
  return `${customPrefix}-${id}`;
}
onMounted(()=> {
  initMap()
})
</script>
<style scoped lang="scss">
.s-map-panel {
  width: 100vw;
  height: 100vh;
  margin: 0;
  padding: 0;
  overflow: hidden;


}

</style>

效果图如下:

image.png

下载

改造版已经打包好,直接下载即可:

下载地址:download.csdn.net/download/m0…