uniapp使用高德获得详细地址
准备工作
本文主要针对uniapp做的。
1.登陆高德地图官网并添加应用获得key 。[高德官网](https://lbs.amap.com/)
如图:
2.下载amap-wx.js。获得文件如下。网站链接: 下载地址
3.把你的HBuilder X打开,并把amap-wx.js导入static文件下。如图:
进入主题
1.初始化
<script>
var amapFile = require('../../../static/js/amap-wx.js'),//引入刚刚下载的文件
//设置初始化
markersData = {
latitude: '',//纬度
longitude: '',//经度
key: "xxxxxxxxxxxxxxxxxxxxxxxx"//申请的高德地图key
}
<script>
2.授权、获得经纬度、经纬度转地址
async getLocation() {
this.getSetting();
this.doGetLocation();
},
/* 获得经纬度 */
doGetLocation() {
uni.getLocation({
type: 'wgs84',
success: (res) => {
this.loadCity(res.latitude,res.longitude);
},
fail: (err) => {
uni.showToast({
title: "获取失败"
})
}
})
},
/* 是否授权,没有授权则授权*/
getSetting: function() {
return new Promise((resolve, reject) => {
uni.getSetting({
success: (res) => {
if (res.authSetting['scope.userLocation'] === undefined) {
resolve(0);
return;
}
if (res.authSetting['scope.userLocation']) {
resolve(1);
} else {
resolve(2);
}
}
});
});
},
//把当前位置的经纬度传给高德地图,调用高德API获取当前地理位置
//其他的API 地址:https://lbs.amap.com/api/wx/reference/core
loadCity: function (latitude, longitude) {
var that = this;
var myAmapFun = new amapFile.AMapWX({ key: markersData.key });
myAmapFun.getRegeo({
location: '' + longitude + ',' + latitude + '',//location的格式为'经度,纬度'
success: function (e) {
city= e[0].regeocodeData.addressComponent.city;//城市
province= e[0].regeocodeData.addressComponent.province;//省份
console.log(" province"+province+" city"+city)
},
fail: function (info) {
console.log("失败");
}
});
}
}