Vue项目中集成百度地图组件
应用场景
在Vue应用中集成百度地图,实现位置展示、标记创建、坐标获取等功能
前提条件
百度开发者账号及地图API访问密钥(AK)
组件实现
<template>
<div id="map-container"></div>
</template>
<script>
export default {
name: "BMapComponent",
data: () => ({
mapInstance: null,
currentMarker: null
}),
methods: {
initialize(config) {
this.loadMapScript(config);
},
loadMapScript(config) {
const scriptTag = document.createElement('script');
scriptTag.src = `https://api.map.baidu.com/getscript?v=3.0&ak=${config.ak}`;
document.body.appendChild(scriptTag);
scriptTag.onload = () => this.setupMap(config);
},
setupMap(config) {
this.mapInstance = new BMap.Map("map-container", {
coordsType: config.coordType
});
if(this.checkMapStatus()) {
const center = new BMap.Point(config.center.lng, config.center.lat);
this.mapInstance.centerAndZoom(center, config.zoomLevel);
this.mapInstance.enableScrollWheelZoom(config.enableZoom);
if(config.showMarker) {
this.clearMarkers();
this.createMarker(config.markerPosition, config.draggable);
}
} else {
console.error("地图初始化失败");
}
},
searchLocation(keyword) {
if(this.mapInstance) {
new BMap.LocalSearch(this.mapInstance, {
renderOptions: { map: this.mapInstance }
}).search(keyword);
}
},
checkMapStatus() {
return !!this.mapInstance;
},
clearMarkers() {
this.mapInstance && this.mapInstance.clearOverlays();
},
getMarkerPosition() {
return this.currentMarker?.getPosition();
},
createMarker(position, draggable) {
if(window.BMap) {
this.currentMarker = new BMap.Marker(position, { enableDragging: draggable });
this.mapInstance.addOverlay(this.currentMarker);
}
},
getMapCenter() {
const center = this.mapInstance.getCenter();
return { lng: center.lng, lat: center.lat };
},
resetMapView() {
this.mapInstance.reset();
},
setMapCenter(lng, lat) {
this.mapInstance.setCenter(new BMap.Point(lng, lat));
}
}
};
</script>
<style>
#map-container {
width: 100%;
height: 400px;
}
</style>
组件引用
<template>
<div class="map-wrapper">
<b-map-component ref="mapRef"></b-map-component>
</div>
</template>
<script>
import BMapComponent from "@/components/BMapComponent.vue";
export default {
components: { BMapComponent }
};
</script>
使用示例
从数据源获取配置参数:
const mapConfig = {
ak: "your_baidu_ak",
coordType: 5,
center: { lng: 116.404, lat: 39.915 },
zoomLevel: 15,
enableZoom: true,
showMarker: true,
markerPosition: { lng: 116.404, lat: 39.915 },
draggable: true
};
初始化地图组件:
this.$refs.mapRef.initialize(mapConfig);
添加标记示例:
addNewMarker() {
this.$refs.mapRef.clearMarkers();
const center = this.$refs.mapRef.getMapCenter();
this.$refs.mapRef.createMarker(center, true);
}