以下代码可实现小程序内位置获取方案
粘贴即可使用,需要用到的地方导入调用就行了。
代码拆分为两个模块:
- 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"
]
文章提供了一种实现小程序内获取用户位置的优化方案,包括两个独立模块:getAuth_userLocation用于判断并处理用户位置授权,getUserLocation用于获取经纬度信息。代码结构清晰,耦合度低,具有更高灵活性。在用户未授权时,引导用户进行授权,并在获取位置信息失败时处理授权问题。需在app.json中配置权限描述以避免调用错误。

被折叠的 条评论
为什么被折叠?



