uniapp接口文档 uni.getLocation(OBJECT) | uni-app官网
高德逆地理解析接口文档 地理/逆地理编码-API文档-开发指南-Web服务 API | 高德地图API
封装js代码,获取到当前的坐标,逆地理编码解析,定位权限拒绝处理
// 获取地理位置解析完成的
export async function getLocationOnce() {
const location = await getLocation()
if(!location) return false
const res = await locationReverseInfoFix(location)
return res // 北京市东城区东华门街道正义路北京市人民政府(旧址)
}
// 获取地理位置(经纬度) 参照uniapp官网 https://uniapp.dcloud.io/api/location/location.html
export async function getLocation() {
if(!(await judgeAuthScope())) return false // 是否有定位权限判断并进行处理
return new Promise((resolve, reject) => {
uni.getLocation({
type: 'gcj02', // 默认为 wgs84 返回 gps 坐标,gcj02 返回国测局坐标
geocode: true, //设置该参数为true可直接获取经纬度及城市信息
isHighAccuracy: true, // 开启高精度定位 微信小程序 (基础库 2.9.0+)
highAccuracyExpireTime: 3000, // 高精度定位超时时间(ms),指定时间内返回最高精度,该值3000ms以上高精度定位才有效果
timeout: 5,
success: function (data) {
resolve(data)
},
fail: function (err) {
uni.showToast({
title: '获取地址失败,将导致部分功能不可用',
icon: 'none'
});
reject(err)
}
});
})
}
// 逆地理解析结果处理,传入经纬度
export async function locationReverseInfoFix(mylocation) {
const location = "&location=" + mylocation.longitude + "," + mylocation.latitude;
const res = await getLocationInfoReverse(location)
if (res.statusCode == 200 && res.data.infocode == "10000") {
const reslove = res.data.regeocode.formatted_address
uni.setStorageSync('getLocation', reslove)
return reslove
} else if (res.data.infocode !== "10000") {
uni.showToast({
icon: 'none',
title: '高德秘钥已过期,请及时更新',
duration: 2000
})
return false
} else {
uni.showToast({
icon: 'none',
title: '地址获取转换失败',
duration: 2000
})
return false
}
}
// 高德逆地理解析请求
export function getLocationInfoReverse (location) {
// 高德地图API,经纬度转位置信息
const key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' //高德key秘钥
let reqUrl = 'https://restapi.amap.com/v3/geocode/regeo?key=' + key + location
return new Promise((resolve, reject) => {
uni.request({
method: 'GET',
url: reqUrl,
success: (res) => {
// console.log(res, '转地址')
resolve(res)
},
fail: (err) => {
resolve(err)
// console.log(err, '转地址失败')
}
})
})
}
// 判断用户授权信息
export function judgeAuthScope() {
return new Promise(resolve => {
uni.authorize({
scope: 'scope.userLocation',
success() {
console.log('用户已授权');
resolve(true)
},
fail(e) {
if (e.errMsg.includes('auth deny')) {
// authorize:fail 系统错误,错误码:-12006,auth deny , 用户拒绝错误代码
// 用户未授权
uni.showModal({
title: '授权提醒',
content: '请授权地理位置信息,以便为您提供更好的服务',
cancelText: "取消",
confirmText: '授权',
success: function (showres) {
if (showres.confirm) {
// 打开设置
uni.openSetting({
success(res) {
// console.log(res.authSetting)
},
fail(err) {
console.log(err);
}
});
// console.log('用户点击确定');
} else if (showres.cancel) {
// console.log('用户点击取消');
}
}
})
} else {
uni.showToast({
title: '未获取到地理位置授权',
icon: 'none'
});
}
console.log('用户未授权', e);
resolve(false)
}
})
})
}
附、去高德创建秘钥
名称类型随便填