这次使用的原理还是引用bmapGl.js这个文件,并不是引用模块,可能是因为对于Vue模块管理不够了解,模块引用死活整不上去,话不多说开始正题。
1.创建bmpgl.js
//BMapGL
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);
});
}
这里的ak是变量,代表的是你申请的秘钥。
2.创建bmap.vue
<template>
<div id="container"></div>
</template>
<script>
import {BMPGL} from "../../assets/js/bmap/bmpgl.js";
export default {
name:'map',
data(){
return{
ak:"你的秘钥",
};
},
mounted(){
this.initMap();
},
methods:{
initMap(){
BMPGL(this.ak)
.then(BMapGL => {
//创建地图实例
let map = new BMapGL.Map("container");
map.centerAndZoom("北京市",5);
map.enableScrollWheelZoom(true);
map.setMapType(BMAP_EARTH_MAP);
})
}
}
}
</script>
<style>
/* The container of BaiduMap must be set width & height. */
#container {
overflow: hidden;
width: 100%;
height: 100%;
margin: 0;
font-family: "微软雅黑";
}
</style>
代码就这么多。