vue的百度地圖早就有vue-baidu-map這里就不贅述了蒋院,
自己去直接對(duì)著API寫(xiě)就好了亏钩,基本上已經(jīng)滿足絕大多數(shù)需求了還簡(jiǎn)單方便。
vue-baidu-map 傳送門(mén) https://dafrok.github.io/vue-baidu-map/#/zh/index
這里主要是在vue里面引入BMapGL欺旧,或者其他個(gè)性化地圖姑丑。
另外還有一篇文章是更加去全面的關(guān)于 BMapGL + BMapGLLib 引入的:
vue引入百度地圖BMapGL,以及輔助工具BMapGLLib 的引入辞友,BMapGL鼠標(biāo)繪制功能栅哀。【點(diǎn)擊進(jìn)去】
因?yàn)楫惒降膯?wèn)題直接index.html引入會(huì)報(bào)錯(cuò),所以采用以下方式
關(guān)于地圖異步這個(gè)問(wèn)題這里啰嗦一下(年紀(jì)大了就是喜歡啰嗦称龙?):
地圖組件渲染完畢時(shí)觸發(fā)留拾,返回一個(gè)百度地圖的核心類和地圖實(shí)例。百度地圖組件是異步加載鲫尊,請(qǐng)不要嘗試在組件的生命周期中訪問(wèn) BMap 核心類和 map 實(shí)例痴柔,如有需要,請(qǐng)?jiān)谒杞M件的 ready 事件回調(diào)函數(shù)的參數(shù)中獲取疫向。
——【vue-baidu-map咳蔚,全局組件事件】
地圖沒(méi)有生成的時(shí)候不要進(jìn)行任何對(duì)地圖的操作。
譬如說(shuō)你的坐標(biāo)中心點(diǎn)初始化是要從后臺(tái)獲取數(shù)據(jù)進(jìn)行初始化定位的搔驼。
一定要等到地圖渲染完成以后再進(jìn)行操作谈火。也就是關(guān)于地圖的初始化數(shù)據(jù)接口的請(qǐng)求要放在地圖ready里面。(這方面出錯(cuò)容易引起的錯(cuò)誤例子:一開(kāi)始地圖空白舌涨,刷新一下就好了什么的糯耍。。泼菌。map報(bào)錯(cuò)谍肤。map, BMap,undefined什么的。哗伯。荒揣。。)
文件源碼地址
GitHub地址:https://github.com/zmannnnn/bmpGL | 【點(diǎn)擊跟蹤源碼地址】
文件結(jié)構(gòu)圖解
在src里面創(chuàng)建一個(gè)bmpgl.js
其實(shí)建立在哪看你自己的意愿啦焊刹。(小聲逼逼)
// bmpgl.js
export function BMPGL(ak) {
return new Promise(function(resolve, reject) {
window.init = function() {
// eslint-disable-next-line
resolve(BMapGL)
}
const script = document.createElement('script')
script.type = 'text/javascript'
script.src = `http://api.map.baidu.com/api?v=1.0&type=webgl&ak=${ak}&callback=init`
script.onerror = reject
document.head.appendChild(script)
})
}
vue頁(yè)面里面引入
<template>
<div class="home">
<!--創(chuàng)建地圖容器-->
<div id="container" class="allmap"></div>
</div>
</template>
<script>
import { BMPGL } from "@/bmpgl.js"
export default {
name: "home",
data() {
return {
ak: "XXXXXXXXX", // 百度的地圖密鑰
myMap: null
};
},
mounted() {
this.initMap()
},
methods: {
initMap() {
// 傳入密鑰獲取地圖回調(diào)系任。
BMPGL(this.ak).then((BMapGL) => {
// 創(chuàng)建地圖實(shí)例
let map = new BMapGL.Map("container");
// 創(chuàng)建點(diǎn)坐標(biāo) axios => res 獲取的初始化定位坐標(biāo)
let point = new BMapGL.Point(114.031761, 22.542826)
// 初始化地圖,設(shè)置中心點(diǎn)坐標(biāo)和地圖級(jí)別
map.centerAndZoom(point, 19)
//開(kāi)啟鼠標(biāo)滾輪縮放
map.enableScrollWheelZoom(true)
map.setHeading(64.5)
map.setTilt(73)
// 保存數(shù)據(jù)
// this.myMap = map
})
.catch((err)=>{
console.log(err)
})
},
}
};
</script>
<style lang="scss" scoped>
.allmap {
width: 100%;
height: 100vh;
position: relative;
z-index: 1;
}
</style>