看了下官网上的方法,是采用原生的写法,不适用于vue
异步引入的好处是baiduAK可以方便管理
import { baiduAk } from '@/settings'
export function map() {
/* eslint-disable */
return new Promise(function(resolve, reject) {
if (typeof (BMap) !== 'undefined') return resolve(BMap)
var script = document.createElement('script')
script.type = 'text/javascript'
script.src = `http://api.map.baidu.com/api?v=2.0&ak=${baiduAk}&callback=init`
script.onerror = reject
document.head.appendChild(script)
const timer = setInterval(() => {
if (BMap) {
resolve(BMap)
clearInterval(timer)
}
}, 500)
})
}
此代码特殊在于使用了定时器循环resolve(BMap),因异步原因,有时无法正常返回BMap,故采用此写法
引入方式
import { map } from '@/utils/map'
使用方式
this.$nextTick(() => {
map().then(BMap => {
this.map = new BMap.Map('allmap', { enableMapClick: false })
const point = new BMap.Point(longitude, latitude)
this.map.centerAndZoom(point, 17)
this.map.enableScrollWheelZoom() // 启用滚轮放大缩小,默认禁用
this.map.enableContinuousZoom() // 启用地图惯性拖拽,默认禁用
})
})