项目中需要用百度地图计算两个坐标点的距离,在项目中引入vue-baidu-map后,组件中没有找不到BMap对象,一番寻找后。。。正确使用方式如下
1、在项目中引入vue-baidu-map
main.js中
import BaiduMap from 'vue-baidu-map'
Vue.use(BaiduMap, {
ak: '你的密钥'
})
2、在组件中使用需要先加载地图组件才可以使用BMap,不需要显示地图组件可以让他隐藏
<div v-show="false">
<baidu-map @ready="onMapReady"/>
</div>
methods: {
//检测地图加载完成
onMapReady({BMap, map}) {
this.BMap = BMap;
},
getDistance(p1, p2) {
try {
const _this = this;
const BMap = this.BMap;
const driving = new BMap.DrivingRoute(new BMap.Point(116.404, 39.915), {
onSearchComplete: function (results) {
_this.distance = Math.floor((results.taxiFare.distance)/1000)// 公里数
}
});
driving.search(p1, p2);
} catch (e) {
console.warn(e, 'e')
}
},
handleAddressChange() {
const BMap = this.BMap;
if(!BMap) return;
const p1 = new BMap.Point(Longitude1, Latitude1);
const p2 = new BMap.Point(Longitude2, Latitude2);
this.getDistance(p1, p2)
}
}