一开始我是直接用uniapp的map组件来展示地图的,申请百度地图key值后用uni.getlocation来获取位置信息的,但是这只能获取到经纬度,拿不到城市信息,即使设置了geocode为true也不行。
methods:{
getLocal(){
uni.getLocation({
type: 'wgs84',
geocode:true,
success: function (res) {
this.longitude=res.longitude
this.latitude=res.latitude
console.log('当前位置的经度:' + res.longitude);
console.log('当前位置的纬度:' + res.latitude);
}
});
}
}
然后就换了一种方法,在终端下载vue-baidu-map
npm install vue-baidu-map --save
然后在main.js中引入
//引入百度地图api
import BaiduMap from 'vue-baidu-map'
Vue.use(BaiduMap, { ak: 'ghKEGlOd60y0hN3kqBqSrivpsB3KQzkTG' })
然后就可以按照百度开发平台的步骤来了,可以和vue-baidu-map的官网结合来看
methods:{
map_handler({
BMap,
Map
}){
this.BMap = BMap;
this.map = map;
var map = new BMap.Map("map");
var point = new BMap.Point(116.331398,39.897445);
map.centerAndZoom(point,12);
var geolocation = new BMap.Geolocation();
geolocation.getCurrentPosition(r=>{
var mk=new BMap.Marker(r.point)
map.addOverlay(mk)
map.panTo(r.point)
console.log("您的位置"+r.point.lng+","+r.point.lat);
this.center=`${r.point.lng},${r.point.lat}`
// 创建地理编码实例, 并配置参数获取乡镇级数据
var myGeo = new BMap.Geocoder({extensions_town: true});
// 根据坐标得到地址描述
myGeo.getLocation(new BMap.Point(r.point.lng, r.point.lat), function(result){
if (result){
console.log(result.address+result.business);
}
});
})
},
}
需要注意的是对地图的操作一定要写在map_handler()后才有效
这样就可以成功获取到城市信息了
以下是html的代码
<template>
<view>
<baidu-map id="map" :center="center" @ready="map_handler">
<bm-geolocation anchor="BMAP_ANCHOR_BOTTOM_RIGHT" :showAddressBar="true" :autoLocation="true"></bm-geolocation>
</baidu-map>
</view>
</template>