效果图:
在APP端使用uni.chooseLocation()可以获取到经纬度和地址全称,但是无法获取到单独的省市区名称和编码,我们可以借助高德地图的api接口来实现:
1.使用uni.chooseLocation()获取到经纬度数据;
2.使用高德api获取到省市区详细信息,下面是api接口地址:
https://restapi.amap.com/v3/geocode/regeo?output=JSON&location=经度,纬度&key=高德地图key
注:高德地图key申请地址:https://console.amap.com/dev/key/app
3.在manifest.json --> App模块配置中, 勾选maps地图选项,选用百度地图或者高德地图均可,填写相应平台申请的key值
代码如下:
let [err, address] = await uni.chooseLocation(obj)
if (!err) {
// 使用高德地图API查询省市区编码
const amapKey = config.mapWebKey; // 替换为你的高德地图API Key
const amapUrl = `https://restapi.amap.com/v3/geocode/regeo?output=JSON&location=${address.longitude},${address.latitude}&key=${amapKey}`;
uni.request({
url: amapUrl,
success: async (res) => {
if (res.statusCode === 200) {
const { province, city, district } = res.data.regeocode.addressComponent;
// 省市区名称
address.addressName = province + city + district;
// 区域编码
const districtCode = res.data.regeocode.addressComponent.adcode
// 根据区域编码获取省市区编码
let ads = await this.getAreaInfoList(districtCode)
address = {
...address,
...ads
}
console.log(address, '---address')
}
}
})
}