微信小程序使用wx.getLocation获取定位,点击取消后打开手机设置,重新获取定位
阐述
在某些场景下,我们需要使用微信小程序获取定位信息,比如说小编这个打卡的功能,在用户每次打卡的时候都需要获取用户的位置。如果用户不在位置范围,则打卡失败。
实现办法如下:
1,调用微信小程序的wx.getLocation,获取用户位置
2,使用wx.openSetting重新唤起手机设置,获取定位
PS:如果用户点击取消的情况下才会使用wx.openSetting次API
一、调用微信小程序的wx.getLocation,获取用户位置
-
使用wx.getLocation地址:https://developers.weixin.qq.com/miniprogram/dev/api/location/wx.getLocation.html
-
wx.getLocation使用代码如下:
- 根据自己的需求使用获取位置方法,可以直接在页面加载完成以后,在onLoad生命周期函数里面直接调用。也可以通过绑定点击事件来唤起获取用户位置
kqdk(){
wx.getLocation({
type: 'wgs84',
success (res) {
const latitude = res.latitude
const longitude = res.longitude
const speed = res.speed
const accuracy = res.accuracy
console.log('获取定位',res)
},
fail(error){
consloe.log('用户拒绝获取位置信息')
}
}
二、使用wx.openSetting打开手机设置,获取位置信息
https://developers.weixin.qq.com/miniprogram/dev/api/open-api/setting/wx.openSetting.html
ps:此API适用于用户点击失败拒绝获取位置,重新打开手机设置,获取位置信息。
wx.openSetting打开手机设置有两种办法如下:
1,使用 button 组件来使用此功能,示例代码如下:
<button open-type="openSetting" bindopensetting="callback">打开设置页</button>
2,使用wx.showModal模态框,也可以唤起wx.openSetting,打开手机设置
wx.showModal({
title:'温馨提示',
content:'小程序将获取您的授权用来显示位置信息',
success(res){
if(res.confirm){
console.log('点击了确认');
wx.openSetting({
success (res) {
console.log(res.authSetting)
res.authSetting = {
"scope.userInfo": true,
"scope.userLocation": true
}
}
})
}else{
console.log('点击了取消')
}
}
})