首先,先去百度地图开放平台申请一个ak秘钥
在自己的vue项目里面的index.html页面里 先引用百度地图的cdn
<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=你申请的ak秘钥&s=1" ></script>
然后再vue.config.js中进行配置百度地图,不然会出现 BMap is not defined的错误
configureWebpack:{
externals: {"BMap": "BMap"}
}
创建一个map.js文件,这样做的目的是为了在百度地图加载完之后再进行调用,不然拿不到百度地图对象
// map.js
export default function MP() {
return new Promise(function (resolve, reject) {
window.onload = function () {
resolve(BMap)
}
})
}
在你需要用到百度地图的vue文件中
<template>
<van-popup
:close-on-click-overlay="false"
v-model="show"
position="top"
@close="mapClose"
@open="open"
:style="{ height: '100%' }"
>
<div class="BMap">
<div class="search">
<div class="back middleCenter" @click="back">
<van-icon name="arrow-left" color="#fff" />
</div>
<div class="searchContent middleCenter">
<van-search
v-model="keyword"
id="keywordId"
placeholder="搜索位置"
@input="querySearch"
v-if="isShow"
></van-search>
<div id="searchResultPanel" style="border:1px solid #C0C0C0;width:150px;height:auto; display:none;"></div>
</div>
<div class="addressListWrap">
<div class="item" v-for="(address,index) in addressList" :key="index" @click="selectAddress(address)">
{{address.value}}
<span>{{address.label}}</span>
</div>
</div>
</div>
<div class="map" id="allMap"></div>
<div class="currentAddress">
<div class="middleCenter">当前位置</div>
<div class="addressName middleCenter">{{currentAddress}}</div>
<div class="btnWrap middleCenter"><van-button type="primary" size="small">确定</van-button></div>
</div>
</div>
</van-popup>
</template>
<script>
import MP from './bMap/map.js'
import {isEmpty} from '@/utils/index'
export default {
name:'BMap',
data () {
return {
keyword:'',
mapCenter:'',
isShow:false,
addressList:[],
currentAddress:''
}
},
props:{
visible:{
required:true,
type:Boolean,
default:false
},
},
computed:{
show:{
get(){
return this.visible
},
set(v){
this.$emit('close',v)
}
}
},
created(){
MP()
},
methods:{
back(){
this.$emit('close')
},
open(){
this.isShow = true
this.$nextTick(function(){
this.initMap()
})
},
getAddressName(pt){
const THIS = this
return new Promise(resolve=>{
var geoc = new BMap.Geocoder();
geoc.getLocation(pt, function(rs){
console.log(rs)
var addComp = rs.addressComponents;
const {surroundingPois,addressComponents:{street}} = rs
let name =''
if(surroundingPois.length>0){
name = surroundingPois[0].title
}else{
name = street
}
THIS.currentAddress = name
resolve(name)
// console.log(addComp)
// console.log(rs)
// console.log(addComp.province + ", " + addComp.city + ", " + addComp.district + ", " + addComp.street + ", " + addComp.streetNumber);
// // alert(addComp.province + ", " + addComp.city + ", " + addComp.district + ", " + addComp.street + ", " + addComp.streetNumber);
});
})
},
selectAddress(item){
this.mapClose()
console.log(item.value)
},
mapClose(){
this.addressList = []
this.keyword = ''
this.$emit('close')
this.isShow = false
},
async initMap(){
const that = this
var map = new BMap.Map("allMap"); // 创建Map实例
const lnglat = await this.getCurrentAddress(map)
const currentAddress= isEmpty(this.mapCenter) ? this.mapCenter : new BMap.Point(lnglat.lng, lnglat.lat)
map.centerAndZoom(currentAddress, 18); // 初始化地图,设置中心点坐标和地图级别
map.setCurrentCity("北京"); // 设置地图显示的城市 此项是必须设置的
// map.enableScrollWheelZoom(true);
var ac = new BMap.Autocomplete( //建立一个自动完成的对象
{
"input" : "keywordId"
,"location" : map
,onSearchComplete:function(result){
console.log(result)
var s = []
const hrList = result.Hr
for (var i = 0; i < hrList.length; i++) {
var x = hrList[i]
var item = { value: x.business, label: x.city+x.district }
s.push(item)
}
that.addressList = s
}
}
);
},
addMarker(map,point){
const THIS = this
map.clearOverlays() // 清楚所有的覆盖物
const marker = new BMap.Marker(point); // 创建marker
map.addOverlay(marker); // 将覆盖物添加到地图中
map.panTo(point); // 重新设置中心点
marker.enableDragging(); // 允许覆盖物可以拖动
marker.addEventListener("dragend", function(e){ // 覆盖物的拖动事件
THIS.getAddressName(e.point).then(res=>{
console.log(res)
})
})
},
getCurrentAddress(map){ // 获取当前地点
const THIS = this
return new Promise((resolve,reject)=>{
var geolocation = new BMap.Geolocation();
geolocation.getCurrentPosition(function(r){
if(this.getStatus() == BMAP_STATUS_SUCCESS){
const {point} = r
THIS.addMarker(map,point)
const lnglat={
lng:point.lng,
lat:point.lat
}
resolve(lnglat)
}
else {
alert('failed'+this.getStatus());
}
},{enableHighAccuracy: true})
})
},
querySearch(v) {
this.keyword = v
if(!isEmpty(v)){
this.addressList = []
}
}
},
}
</script>
<style lang='stylus' scoped>
.BMap{
width 100%
height 100%
background #fff
display flex
flex-direction column
.search{
position relative
display flex
background #06c05e
height 50PX
.addressListWrap{
position absolute
top 50PX
width 100%
height auto
background #fff
z-index 99999
.item{
border-bottom 1px solid #eee
padding 20px 10px
font-size 30px
color #333
span{
color #cccccc
font-size 26px
}
}
}
.back{
padding 0 40px 0 20px
}
.searchContent{
flex 1
padding-right 40px
>>>.van-search{
background #06c05e
padding-left 0
width 100%
padding 0
}
>>>.van-search__action{
color #fff
}
}
}
.map{
flex 1
}
.currentAddress{
height 100px
display flex
padding 0 20px
font-size 30px
color #333
.addressName{
flex 1
padding 0 20px
}
}
}
</style>
最后的效果