一、在index.html文件中引入百度地图
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vue 2 BMap Demo</title>
<script src="https://api.map.baidu.com/api?v=3.0&ak=你的_KEY"></script>
</head>
<body>
<div id="app"></div>
<script src="/dist/build.js"></script>
</body>
</html>
二、创建map.vue地图组件
<template>
<div class="bmap-search-marker">
<input type="text" v-model="keyword" placeholder="请输入关键字">
<button @click="search">搜索</button>
<div ref="mapContainer" class="map-container"></div>
<div v-if="marker">
<p>经度:{{ marker.lng }}</p>
<p>纬度:{{ marker.lat }}</p>
<p>地址:{{ marker.address }}</p>
</div>
</div>
</template>
<script>
export default {
data() {
return {
keyword: '',
map: null,
marker: null
};
},
mounted() {
this.loadMap();
this.map.addEventListener("click", (e) => {
this.handleMapClick(e.point);
});
},
methods: {
loadMap() {
this.map = new BMap.Map(this.$refs.mapContainer);
this.map.centerAndZoom(new BMap.Point(116.404, 39.915), 13);
const navigationControl = new BMap.NavigationControl();
this.map.addControl(navigationControl);
},
search() {
if (!this.keyword) return;
const localSearch = new BMap.LocalSearch(this.map, {
onSearchComplete: (results) => {
if (localSearch.getStatus() === BMAP_STATUS_SUCCESS) {
const poi = results.getPoi(0);
if (this.marker) {
this.map.removeOverlay(this.marker);
}
const marker = new BMap.Marker(poi.point);
this.map.addOverlay(marker);
this.marker = {
lng: poi.point.lng,
lat: poi.point.lat,
address: poi.address
};
}
}
});
localSearch.search(this.keyword.trim());
},
handleMapClick(point) {
if (this.marker) {
this.map.removeOverlay(this.marker);
}
const marker = new BMap.Marker(point);
this.map.addOverlay(marker);
this.marker = {
lng: point.lng,
lat: point.lat,
address: ''
};
const geoc = new BMap.Geocoder();
geoc.getLocation(point, (result) => {
if (geoc.getStatus() === BMAP_STATUS_SUCCESS) {
this.marker.address = result.address;
}
});
}
}
};
</script>
<style scoped>
.map-container {
width: 100%;
height: 400px;
}
</style>```
## 三、vue文件中使用
```javascript
<template>
<div>
<map/>
</div>
</template>
<script>
import map from './map.vue';
export default {
components: {
map
}
};
</script>