<template>
|
<div class="map-wrapper">
|
<div ref="mapContainer" class="map-container"></div>
|
</div>
|
</template>
|
|
<script>
|
let baiduMapPromise = null;
|
|
function loadBaiduMapScript() {
|
const ak = 'H4IN9QhFD5mC72tJEvbZysO7SKf0vDMa';
|
if (window.BMapGL) {
|
return Promise.resolve();
|
}
|
if (baiduMapPromise) {
|
return baiduMapPromise;
|
}
|
baiduMapPromise = new Promise((resolve, reject) => {
|
window.__baidu_map_callback = function() {
|
delete window.__baidu_map_callback; // 清理全局回调
|
resolve();
|
};
|
const script = document.createElement('script');
|
script.type = 'text/javascript';
|
script.src = `//api.map.baidu.com/api?type=webgl&v=1.0&ak=${ak}&callback=__baidu_map_callback`;
|
script.onerror = (error) => {
|
delete window.__baidu_map_callback;
|
baiduMapPromise = null; // 允许重试
|
reject(error);
|
};
|
document.body.appendChild(script);
|
});
|
return baiduMapPromise;
|
}
|
import { getCurrentPosition } from '@/utils/tool.js'
|
|
export default {
|
name: 'BaiduMap',
|
props: {
|
center: {
|
type: Object,
|
default: () => ({ lng: 0, lat: 0 })
|
},
|
},
|
data() {
|
return {
|
map: null,
|
zoom: 17,
|
userPosition: null
|
};
|
},
|
mounted() {
|
this.loadMap();
|
},
|
beforeUnmount() {
|
if (this.map) {
|
this.map.destroy();
|
this.map = null;
|
}
|
},
|
methods: {
|
loadMap() {
|
loadBaiduMapScript()
|
.then(() => {
|
this.initMap();
|
})
|
.catch(err => {
|
this.$emit('getMapStatus', 'fail')
|
console.error('地图脚本加载失败:', err);
|
});
|
},
|
initMap() {
|
const container = this.$refs.mapContainer;
|
if (!container) return;
|
const map = new BMapGL.Map(container);
|
const point = new BMapGL.Point(this.center.lng, this.center.lat);
|
map.centerAndZoom(point, this.zoom);
|
map.enableScrollWheelZoom();
|
this.map = map;
|
this.$emit('ready', map);
|
this.getUserPosition()
|
},
|
async getUserPosition() {
|
const geolocation = new BMapGL.Geolocation();
|
let that = this
|
geolocation.getCurrentPosition(function(r){
|
if(this.getStatus() == BMAP_STATUS_SUCCESS){
|
// 定位成功,r.point 即为获取到的百度坐标(BD09ll)
|
let pt = r.point;
|
that.userPosition = {
|
lng: pt.lng,
|
lat: pt.lat
|
}
|
that.$emit('getUserPositionStatus', 'success')
|
that.diffDistance()
|
} else {
|
that.$emit('getUserPositionStatus', 'fail')
|
}
|
});
|
},
|
diffDistance() { //测距
|
if (!this.map || !this.userPosition) return
|
const userPoint = new BMapGL.Point(this.userPosition.lng, this.userPosition.lat); // 点A坐标
|
const centerPoint = new BMapGL.Point(this.center.lng, this.center.lat); // 点B坐标
|
const distance = this.map.getDistance(userPoint,centerPoint)
|
this.$emit('getDistance', Math.floor(distance))
|
}
|
}
|
};
|
</script>
|
|
<style scoped>
|
.map-wrapper {
|
width: 100%;
|
height: 100%;
|
margin: 0;
|
padding: 0;
|
}
|
.map-container {
|
width: 100%;
|
height: 100%;
|
margin: 0;
|
padding: 0;
|
}
|
</style>
|