Last active
April 18, 2024 19:54
-
-
Save nanxiaobei/ce29a4232be37781eefcfef017a486f0 to your computer and use it in GitHub Desktop.
小程序位置选择 wx.chooseLocation() 封装一劳永逸 QTMD 版
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* chooseGeo.js | |
* | |
* 小程序 wx.chooseLocation() 获取地理位置,会先请求授权, | |
* 如果用户未授权,那么再次调用,嗯 ... 就没反应了,还以为微信 API 有问题,崩溃了。 | |
* | |
* 这当然是微信为了良好的用户体验,就不让你问了, | |
* 当然,开发的体验就非常不好了,因为这个 API 干了一半的活,罢工了, | |
* 然后,当然就得自己封装一个了。 | |
* | |
* 这是个非常常见的 case,但是,却没有通用的解决方案, | |
* 于是,大家都是自己写一套,无数的程序员写着无数雷同的代码 ... 世界很不美好。 | |
* 于是,我也写了一套,并分享出来,希望可以帮到有缘人,少做一点大家已经做了无数的工作。 | |
* | |
* 大家可根据自己需要修改一些文案,大体就是这样。 | |
*/ | |
const chooseGeo = () => { | |
return wx | |
.chooseLocation() // 获取位置 https://developers.weixin.qq.com/miniprogram/dev/api/location/wx.chooseLocation.html | |
.then((data) => { | |
if (data.name) { | |
return data; | |
} | |
console.log('未选择位置'); // 未选择位置就点了 "确定" | |
}) | |
.catch(({ errMsg }) => { | |
// 未选择位置点了 "取消" | |
if (errMsg.includes('cancel')) { | |
console.log('未选择位置'); | |
return; | |
} | |
// 未授权 | |
return wx | |
.getSetting() // 获取权限信息 | |
.then(({ authSetting }) => { | |
return authSetting['scope.userLocation']; // 获取位置权限 | |
}) | |
.then((userLocation) => { | |
// 校验位置权限 | |
if (userLocation) { | |
return Promise.reject('已授权'); // 已授权 | |
} | |
return wx.showModal({ title: '是否授权位置?', content: '如需添加位置,请先授权' }); // 没有,弹窗请求授权 | |
}) | |
.then(({ confirm }) => { | |
// 判断弹窗选择 | |
if (confirm) { | |
return wx.openSetting(); // 确定,打开授权页 | |
} | |
return Promise.reject('拒绝授权'); // 取消,拒绝授权 | |
}) | |
.then(({ authSetting }) => { | |
// 进入授权页 | |
if (authSetting['scope.userLocation']) { | |
return chooseGeo(); // 授权成功,再次获取位置 | |
} | |
wx.showToast({ title: '授权失败', icon: 'none' }); | |
return Promise.reject('授权失败'); // 未授权位置 | |
}) | |
.catch(console.log); | |
}); | |
}; | |
export default chooseGeo; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment