1. 安装
npm i vue-baidu-map -S
2. 注册组件
main.js
// 全局注册百度地图组件
import BaiduMap from 'vue-baidu-map'
Vue.use(BaiduMap, { ak: 'your_ak' }) // 自行申请
// 按需引入
根据官方文档来
3. 封装组件
src/component/Map.vue
实现一个简单 demo, css 自己写
<template>
<div class="map-wrapper">
<input type="text" v-model="mapSearchConfig.keyword" />
<baidu-map v-bind="mapConfig" v-on="bindMapEvent">
<bm-local-search v-bind="mapSearchConfig"></bm-local-search>
</baidu-map>
<div class="map-info">
<div class="map-address">{{ markerPo.address }}</div>
<div class="lng-lat" v-if="markerPo.lng">
<div>经度:{{ markerPo.lng.toFixed(5) }}</div>
<div>纬度:{{ markerPo.lat.toFixed(5) }}</div>
</div>
</div>
</div>
</template>
<script>
export default {
name: 'TheMap',
data() {
return {
map: undefined, // map 实例
mapConfig: {
center: { lng: 119.98, lat: 30.548 }, // 初始位置
zoom: 14, // 缩放等级
scrollWheelZoom: true, // 允许滚轮缩放地图
style: 'height:200px; width:500px;',
},
/* v-on="{ }" 使用对象语法时不支持任何修饰器 */
bindMapEvent: {
rightclick: this.getClickInfo,
ready: this.onBMapReady,
},
mapSearchConfig: {
keyword: '',
location: '德清', // 搜索范围
panel: false, // 是否展开自带搜索结果面板
autoViewport: true, // 搜索后自动跳转视角
},
//点击过后获取的地址信息
markerPo: {
address: '请于地图上右击鼠标选择具体位置!',
},
marker: null, // 标记点
};
},
props: {
value: { type: String, default: '' }, // 获取后端数据中已存在的点位信息
},
watch: {
value() {
this.initData();
},
},
methods: {
initData() {
if (!this.map || !this.value) {
return;
}
const arr = this.value.split(',');
if (arr.length === 3) {
const [address, lng, lat] = arr;
this.mapConfig.center = { lng, lat };
this.markerPo = { address, lng, lat };
this.addMarker(this.markerPo);
}
},
onBMapReady({ map }) {
this.map = map;
this.initData();
},
getClickInfo(e) {
// 反编码通过点击经纬度获取地名地址
let geoCoder = new BMap.Geocoder();
geoCoder.getLocation(e.point, res => {
const { address, business, point } = res;
this.markerPo = {
address: `${address} ${business ? `(${business})` : ''}`,
...point,
};
this.addMarker(this.markerPo);
/* 下边的代码只取结果第一个会导致一片地方可能始终只有一个经纬度和点位 */
// 获取地名
// let current_point = {};
// current_point = res.surroundingPois.length
// ? res.surroundingPois[0]
// : res;
// const { address, title } = current_point;
// const addressName = `${title ? title + ' (' : ''}${address}${
// title ? ')' : ''
// }`;
// this.markerPo = {
// ...current_point.point,
// address: addressName,
// };
// this.addMarker(this.markerPo);
// this.$emit(
// 'input',
// `${address},${current_point.point.lng},${current_point.point.lat}`,
// );
});
},
addMarker(data) {
// 移除地图上所有点
this.marker && this.map.removeOverlay(this.marker);
// const point = new BMap.Point(data.lng, data.lat);
// this.marker = new BMap.Marker(point); // 创建标注
this.marker = new BMap.Marker(data); // 创建标注
this.map.addOverlay(this.marker); // 将标注添加到地图中
},
},
};
</script>