需要第三方地图的支持 本文以百度地图为例
第一步 安装百度地图插件 npm install vue-baidu-map --save 成功后在main.js 中引入百度地图
import BaiduMap from 'vue-baidu-map'
Vue.use(BaiduMap, {
ak: "rQxHPQX1ua21rWnXzTbUh5KSSUbnefxR"//你自己的ak
})
第二部 在页面中添加百度地图组件 此步骤必须有,不用显示直接 v-show="false"
<view v-show="false">
<baidu-map @ready="onMapReady"/>
</view>
第三部 获取到当前经纬度信息 使用 uniapp 提供的API uni.getLocation({}) ,把返回的经纬度信息提供给百度地图 转换为具体地址
getLocation(){
let _this = this
uni.getLocation({
type: 'wgs84',
success: function (res) {
var point = new _this.BMap.Point(res.longitude,res.latitude);
var gc = new _this.BMap.Geocoder();
gc.getLocation(point, function(rs){
rs = JSON.parse(JSON.stringify(rs))
_this.province = rs.addressComponents.province;
_this.city = rs.addressComponents.city;
_this.county = rs.addressComponents.district || rs.addressComponents.city;
});
},
fail: function (res) {
console.log(res);
},
});
},
下图是返回的 地址信息 需要通过JSON.parse(JSON.stringify(rs)) 深拷贝一下 ,取值就方便多了