vue3中动态引入BMap

vue3中动态引入BMap,第1张

我的项目目前只有几个页面用到地图Api,不想首屏加载地图,因为用的ts,没有方案可以完全跑下来,所以手动补全。

1 在global.d.ts中,在window上添加Bmap

// global.d.ts
declare global {
  interface Window {
    BMap: T
  }
}

2. 在utiles文件夹下新建loadMap.js,注意,如果你的网站是HTTPS类型,加载的资源也需要是HTTPS类型

// loadMap.ts
/**
 * @description 加载百度地图相关资源js
 */
export default function loadBMap(): Promise {
  return new Promise((resolve, reject) => {
    //聚合API依赖基础库,因此先加载基础库再加载聚合API
    ///MarkerClusterer_min.js依赖TextIconOverlay.js。因此先加载TextIconOverlay.js
    const textIconOverlayUrl = 'https://api.map.baidu.com/library/TextIconOverlay/1.2/src/TextIconOverlay.js'
    const markerClusterer_min = 'https://api.map.baidu.com/library/MarkerClusterer/1.2/src/MarkerClusterer_min.js'
    try {
      resolve(
        loadBaiduMapJs().then(() => {
          resolve(
            loadJs(textIconOverlayUrl).then(() => {
              resolve(loadJs(markerClusterer_min))
            })
          )
        })
      )
    } catch (err) {
      reject(err)
    }
  })
}
/**
 * @description 加载百度地图基础组件js
 */
export function loadBaiduMapJs(): Promise {
  const AK = '你的AK'
  const BMap_URL = 'https://api.map.baidu.com/api?v=2.0&ak=' + AK + '&callback=onBMapCallback'
  return new Promise((resolve, reject) => {
    try {
      // 如果已加载直接返回
      const BMap = window.BMap
      if (typeof BMap !== 'undefined') {
        resolve(BMap)
        return true
      }
      window.onBMapCallback = function () {
        resolve(BMap)
      }
      const scriptNode = document.createElement('script')
      scriptNode.setAttribute('type', 'text/javascript')
      scriptNode.setAttribute('src', BMap_URL)
      document.head.appendChild(scriptNode)
    } catch (err) {
      const scriptNode = document.createElement('script')
      scriptNode.setAttribute('type', 'text/javascript')
      scriptNode.onerror = reject
    }
  })
}
/**
 * @description 加载第三方组件js公共方法
 * @param {string} url
 */
export function loadJs(url: string): Promise {
  return new Promise((resolve, reject) => {
    try {
      const scriptNode = document.createElement('script')
      scriptNode.setAttribute('type', 'text/javascript')
      scriptNode.setAttribute('src', url)
      document.head.appendChild(scriptNode)
      scriptNode.onload = () => {
        resolve()
      }
    } catch (err) {
      const scriptNode = document.createElement('script')
      scriptNode.setAttribute('type', 'text/javascript')
      scriptNode.onerror = reject
    }
  })
}

3.  创建store,以供支持在其他文件调用生成的数据

// store 下 geoLocation.ts
import { defineStore } from 'pinia'
import loadBMap from '@/utils/loadBMap'

interface ICoordinateInfo {
  lng: string
  lat: string
}
interface IAddressInfo {
  city: string
}

export const useGeoLocationStore = defineStore('geographicalLocation', {
  state: () => {
    return {
      provinceAndCityInfo: {
        cityName: '',
        provinceName: '',
      },
      coordinateInfo: {
        lng: '',
        lat: '',
      },
    }
  },
  getters: {
    getProvinceAndCityInfo(): ILocationInfo {
      return this.provinceAndCityInfo
    },

    getCoordinateInfo(): ICoordinateInfo {
      return this.coordinateInfo
    },
  },
  actions: {
    async setLocationInfo() {
      navigator.geolocation.getCurrentPosition(async () => {
        // 借助navigator访问用户是否给权限获取地址, pc和mobile都可用,如给了权限就继续执行,不给权限就会自动return
        await loadBMap()
        const BMap = window.BMap
        // 根据Geolocation会更准确些,LocalCity是通过IP在百度地图数据库查询位置,不准确的概率比较大
        const geolocation = new BMap.Geolocation()
        await geolocation.getCurrentPosition(async (result: { point: ICoordinateInfo; address: IAddressInfo }) => {
          if (geolocation.getStatus() === 0) {
            this.coordinateInfo = Object.assign(result.point)
            this.provinceAndCityInfo = Object.assign(result.address)
          }
        })
      })
    },
  },
})


4 .在需要调用的页面调用定位

import { useGeoLocationStore } from '@/store/modules/geoLocation'
const GEOLocationStore = useGeoLocationStore()
GEOLocationStore.setLocationInfo()

        我目前没有用到地图实例,所以就不列出来了待后续更新。。。。。。

对你有用的话留个赞啊

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1323248.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-12
下一篇 2022-06-12

发表评论

登录后才能评论

评论列表(0条)

保存