Vue项目使用天地图

1.引入

官方文档:

天地图API

先去天地图申请注册 然后获取到Token

然后在项目的 public/index.html 文件内 引入天地图官方提供的Script

 <script src="http://api.tianditu.gov.cn/api?v=4.0&tk=你的Token"></script>

2.使用

按照天地图官方的使用方式 在vue项目中使用会直接报错 这是因为在天地图的Script插件中 函数和对象直接挂载到了window顶级对象中

1.初始化地图

我这里是在项目创建了 utils/mapinit.js 文件  mapinit.js 内容如下

// 初始化地图
export default {
  init() {
    return new Promise((resolve, reject) => {
      // 如果已加载直接返回
      if (window.T) {
        console.log('天地图脚本初始化成功...')
        resolve(window.T)
        reject('error')
      }
    })
  },
}

2.页面

<template>
    <div id="mapContent"></div>
</template>

import MapInit from '@/utils/mapinit'
 export default {
    name: 'HomeMap',
    data() {
      return {
        map: null,
        // 地图配置
        lay: null,
      }
    },
    computed: {
      ...mapGetters({
        area: 'zone/area',
      }),
    },
    mounted() {
      this.getMap()
    },
    methods: {
      async getMap() {
        const { data } = await getEquipmentsByAreaId({ areaId: this.area })
        this.deviceList = data.list
        this.mapData = true
        console.log(this.deviceList)
        MapInit.init()
          .then((T) => {
            let imageURL = 'http://t0.tianditu.gov.cn/img_w/wmts?' + 'SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles' + '&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=你的Token'
            //创建自定义图层对象
            this.lay = new T.TileLayer(imageURL, { minZoom: 1, maxZoom: 18 })
            //初始化地图对象
            this.map = new T.Map('mapContent')
            //设置显示地图的中心点和级别
            this.map.centerAndZoom(new T.LngLat(116.40969, 39.89945),14)
            //创建卫星和路网的混合视图
            this.map.setMapType(window.TMAP_HYBRID_MAP)
            //允许鼠标滚轮缩放地图
            this.map.enableScrollWheelZoom()
          })
          .catch()
      },
    },
  }
</script>

<style scoped>
.mapContent{
    width: 500px;
    height: 500px;
}
</style>

猜你喜欢

转载自blog.csdn.net/weixin_46607967/article/details/130921399