项目中引入 vue-baidu-map
main.js注册
import BaiduMap from 'vue-baidu-map'
Vue.use(BaiduMap, {
// ak 是在百度地图开发者平台申请的密钥 详见 http://lbsyun.baidu.com/apiconsole/key */
ak: '需自己申请'
})
组件内引用
<baidu-map
class="map"
:center="center"
:zoom="15"
:scroll-wheel-zoom="true"
@ready="handler"
>
<bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
<bm-marker
v-if="initLocation"
animation="BMAP_ANIMATION_BOUNCE"
:position="center"
>
</bm-marker>
<bm-geolocation anchor="BMAP_ANCHOR_BOTTOM_RIGHT" :showAddressBar="true" :autoLocation="true" @locationSuccess="handleLocationSuccess"></bm-geolocation>
</baidu-map>
data 中申请的值
center: {}, // 默认坐标点
abc: {
lng: '',
lat: ''
},
point: {},
handler ({ BMap, map }) {
map.enableScrollWheelZoom(true)
// map.centerAndZoom('青岛市', 13)
const _this = this
const geolocation = new BMap.Geolocation()
geolocation.getCurrentPosition(function (r) {
_this.point = r.point
_this.center = { lng: r.longitude, lat: r.latitude } // 设置center属性值
_this.initLocation = true
_this.gitGc(r.point)
}, { enableHighAccuracy: true })
window.map = map
// 赋值,方便调用,本节被用到
this.BMap = BMap
this.map = map
},
gitGc (center) {
new this.BMap.Geocoder().getLocation(center, res => {
this.addr = res.address
})
},
// 刷新
handleLocationSuccess ({ point, AddressComponent, marker }) {
this.initLocation = false
const _this = this
_this.point = point
_this.center = { lng: point.lng, lat: point.lat } // 设置center属性值
new this.BMap.Geocoder().getLocation(point, res => {
_this.addr = res.address
})
}