1,引入百度地图
import BaiduMap from 'vue-baidu-map'
使用你引入的百度地图插件(ak是激活码,这要到百度api进行注册获取到。)
Vue.use(BaiduMap, {
ak: ''
})
2,页面里面调用百度地图使用
import {BaiduMap, BmControl, BmView, BmAutoComplete, BmLocalSearch,BmlMarkerClusterer} from 'vue-baidu-map'
components: {
BaiduMap,
BmView,
BmControl,
BmAutoComplete,
BmLocalSearch,
coupleList,
BmlMarkerClusterer
},
// 创建地图
createMap(){
var map = new BMap.Map("allmap"); //在百度地图容器中创建一个地图
var point = new BMap.Point(106.778458, 33.646665);//定义一个中心点坐标
map.centerAndZoom(point,7);//设定地图的中心点和坐标并将地图显示在地图容器中
map.enableDragging();//启用地图拖拽事件,默认启用(可不写)
map.enableScrollWheelZoom();//启用地图滚轮放大缩小
map.enableDoubleClickZoom();//启用鼠标双击放大,默认启用(可不写)
map.enableKeyboard();//启用键盘上下左右键移动地图
var top_right_navigation = new BMap.NavigationControl({anchor: BMAP_ANCHOR_BOTTOM_RIGHT, type: BMAP_NAVIGATION_CONTROL_SMALL}); //右上角,仅包含平移和缩放按钮
/*缩放控件type有四种类型:
BMAP_NAVIGATION_CONTROL_SMALL:仅包含平移和缩放按钮;BMAP_NAVIGATION_CONTROL_PAN:仅包含平移按钮;BMAP_NAVIGATION_CONTROL_ZOOM:仅包含缩放按钮*/
//添加控件和比例尺
map.addControl(top_right_navigation);
window.map = map;//将map变量存储在全局
},
3,遇到问题报错:Bmap is not defined
mounted () {
this.init() .then((BMap) => {
console.log("加载成功...")
this.createMap() ; //创建地图
// this.setMapEvent();//设置地图事件添加控件
this.addMapControl();//获取地图的当前区域
this.addMarker() //向地图中添加marker标注
})
},
methods: {
init(){
console.log("初始化百度地图脚本...");
const AK = " ";
const apiVersion = "2.0";
const timestamp = new Date().getTime();
const BMap_URL = "http://api.map.baidu.com/getscript?v="+ apiVersion +"&ak="+ AK +"&services=&t=" + timestamp;
return new Promise((resolve, reject) => {
if(typeof BMap !== "undefined") {
resolve(BMap);
return true;
}
// 插入script脚本
let scriptNode = document.createElement("script");
scriptNode.setAttribute("type", "text/javascript");
scriptNode.setAttribute("src", BMap_URL);
document.body.appendChild(scriptNode);
// 等待页面加载完毕回调
let timeout = 0;
let interval = setInterval(() => {
// 超时10秒加载失败
if(timeout >= 20) {
reject();
clearInterval(interval);
console.error("百度地图脚本初始化失败...");
}
// 加载成功
if(typeof BMap !== "undefined") {
resolve(BMap);
clearInterval(interval);
console.log("百度地图脚本初始化成功...");
}
timeout += 1;
}, 500);
});
},
}