以下代码可实现小程序内位置获取方案
粘贴即可使用,需要用到的地方导入调用就行了。
代码拆分为两个模块:
- getAuth_userLocation:判断是否授权(若无则拉起位置授权);
- getUserLocation:获取位置信息(返回经纬度信息);
优势在于代码功能清晰独立,比现有方案耦合度更低,灵活性更强。
// 判断是否受授权位置信息,未授权则引导授权并返回授权结果(true/false)
export function getAuth_userLocation(){
return new Promise((resolve,reject)=>{
wx.getSetting({
success (res) {
if (!res.authSetting['scope.userLocation']) {
wx.authorize({
scope: 'scope.userLocation',
success (res) {
resolve(true)
return
},
fail(err){
console.log('拒绝位置授权',err);
wx.showModal({
title: '提示',
content: '需授权您的位置信息,才能继续使用小程序',
// showCancel:false,
confirmText:'去授权',
complete: (res) => {
if (res.cancel) {
resolve(false)
}
if (res.confirm) {
wx.openSetting({
success(res){
if (res.authSetting['scope.userLocation']) {
resolve(true)
}else{
resolve(false)
}
},
fail(res){
resolve(false)
}
})
}
}
})
}
})
}else{
resolve(true)
}
}
})
})
}
// 获取用户位置(经纬度)
export function getUserLocation(){
return new Promise((resolve,reject)=>{
wx.getLocation({
success(res){
console.log(res);
resolve(res)
},
fail: async(err)=>{
console.log('位置获取失败',err);
let authRes = await getAuth_userLocation()
console.log('authRes',authRes);
if (authRes === true) {
let res2 = await getUserLocation()
resolve(res2)
}else{
resolve(false)
console.log('用户拒绝授权');
// // 开启以下代码实现循环授权,直到拿到位置为止(不建议,太流氓了~~)
// let res3 = await getUserLocation()
// resolve(res3)
}
}
})
})
}
别忘了在app.json里配置以下代码,否则api无权调用,会报错。
"permission": {
"scope.userLocation": {
"desc": "您的位置信息将用于定位"
}
},
"requiredPrivateInfos":[
"getLocation"
]