先看看效果图
一、安装相关依赖
npm i --save vue-baidu-map
二、在main.js中引用
import BaiduMap from "vue-baidu-map"
Vue.use(BaiduMap,{
ak: '你的密钥(百度地图开放API官网可免费申请)'
})
三、创建地图工具 map.js
export function MP(ak) {
return new Promise(function (resolve, reject) {
window.init = function () {
resolve(BMap)
}
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://api.map.baidu.com/api?v=2.0&ak="+"你的密钥"+"&callback=init";
script.onerror = reject;
document.head.appendChild(script);
})
}
在需要用到地图的文件引入该工具
import { MP } from "@/utils/map.js";
四、绘制地图
1、创建一个容器展示地图
<div class="map">
<div id="container" style="height: 300px; width: 100%" ref="allmap"></div>
</div>
2、在data中定义需要用到的数据
data() {
return {
dialogMap: false,
mapPointName: "",
mapGetshow: true
}
}
3、定义全局的map地图对象和geocoder地理编码对象
var map;
let geoc = null;
4、创建一个定位地点的方法
mapNameChange() {
let that = this,
point,
marker = null;
let local = new BMap.LocalSearch(map, {
renderOptions: { map: map },
onSearchComplete: (res) => {
if (local.getResults() != undefined) {
map.clearOverlays(); //清除地图上所有覆盖物
if (local.getResults().getPoi(0)) {
point = local.getResults().getPoi(0).point; //获取第一个智能搜索的结果
map.centerAndZoom(point, 10);
marker = new BMap.Marker(point); // 创建标注
map.addOverlay(marker); // 将标注添加到地图中
marker.enableDragging(); // 可拖拽
geoc.getLocation(point, function (rs) {
var addComp = rs.addressComponents;
that.mapPointName =
addComp.province +
", " +
addComp.city +
", " +
addComp.district +
", " +
addComp.street +
", " +
addComp.streetNumber;
});
} else {
console.log("未搜索到结果")
}
} else {
alert("未搜索到结果");
}
},
});
local.search("岳阳楼"); //要展示的地点
},
5、在mounted函数中调用上述方法并绘制地图
mounted() {
this.$nextTick(function () {
var _this = this;
MP(_this.ak).then((BMap) => {
let that = this;
this.dialogMap = !this.dialogMap;
if (that.mapGetshow) {
map = new BMap.Map("container"); //存放地图容器的id
geoc = new BMap.Geocoder();
map.enableScrollWheelZoom();
}
_this.mapNameChange() //调用定位地点的方法
});
});
}