一、安装vue-baidu-map
npm install vue-baidu-map --save
二、全局注册(也可以局部注册,具体参考vue-baidu-map文档)
import Vue from 'vue'import BaiduMap from 'vue-baidu-map'Vue.use(BaiduMap, {// ak 是在百度地图开发者平台申请的密钥 详见 /apiconsole/key */ak: 'YOUR_APP_KEY'})
三、页面中使用组件
1.模板中使用组件
<baidu-mapclass="map-wrap":center="mapData.center":zoom="mapData.zoom"@ready="mapHandler"@click="getLocation"><bm-navigation anchor="BMAP_ANCHOR_TOP_LEFT"></bm-navigation><bm-city-list anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-city-list><bm-geolocationanchor="BMAP_ANCHOR_BOTTOM_RIGHT":showAddressBar="true":autoLocation="true"></bm-geolocation></baidu-map>
2.定义数据
data() {return {//商家信息(包含坐标信息)businessDetail:{}//地图数据mapData: {//中心坐标center: {lng: 0, lat: 0 },//缩放级别zoom: 13},//BMap类BMap: null,//地图对象map: null}},
3.方法事件处理
//地图预处理async mapHandler({BMap, map }) {if (this.businessId) {//可以在此处请求接口获取坐标数据await this.getMallBusinessDetail()}//保存百度地图类this.BMap = BMap//保存地图对象this.map = map//如果一开始坐标存在(编辑的时候)if (this.businessDetail.longitude && this.businessDetail.latitude) {//设置坐标this.mapData.center.lng = this.businessDetail.longitudethis.mapData.center.lat = this.businessDetail.latitude} else {//如果坐标不存在则动态获取当前浏览器坐标(创建的时候)let geolocation = new BMap.Geolocation()//获取当前的坐标(使用promise 将异步转换为同步)await new Promise((resolve) => {geolocation.getCurrentPosition((r) => {this.mapData.center.lng = this.businessDetail.longitude =r.point.lngthis.mapData.center.lat = this.businessDetail.latitude = r.point.latresolve()})})}//创建定位标记let marker = new BMap.Marker(new BMap.Point(this.businessDetail.longitude,this.businessDetail.latitude))//将标记添加到地图上map.addOverlay(marker)},//在地图上选择区域getLocation(e) {//设置经度this.businessDetail.longitude = e.point.lng//设置纬度this.businessDetail.latitude = e.point.lat//百度地图类let BMapGL = this.BMap//地图对象let map = this.map//清除地图上所有的覆盖物(保证每次点击只有一个标记)map.clearOverlays()//创建定位标记let marker = new BMapGL.Marker(new BMapGL.Point(e.point.lng, e.point.lat))//将标记添加到地图上map.addOverlay(marker)//创建坐标解析对象let geoc = new BMapGL.Geocoder()//解析当前的坐标成地址geoc.getLocation(e.point, (rs) => {//获取地址对象let addressComp = rs.addressComponents//拼接出详细地址this.businessDetail.address =addressComp.province +addressComp.city +addressComp.district +addressComp.street +addressComp.streetNumber})},