微信小程序使用wx.getLocation获取定位,点击取消后打开手机设置,重新获取定位

微信小程序使用wx.getLocation获取定位,点击取消后打开手机设置,重新获取定位

阐述

在某些场景下,我们需要使用微信小程序获取定位信息,比如说小编这个打卡的功能,在用户每次打卡的时候都需要获取用户的位置。如果用户不在位置范围,则打卡失败。
在这里插入图片描述

实现办法如下:

1,调用微信小程序的wx.getLocation,获取用户位置
2,使用wx.openSetting重新唤起手机设置,获取定位

PS:如果用户点击取消的情况下才会使用wx.openSetting次API

一、调用微信小程序的wx.getLocation,获取用户位置
  1. 使用wx.getLocation地址:https://developers.weixin.qq.com/miniprogram/dev/api/location/wx.getLocation.html

  2. 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('点击了取消')
          }
        }
      })

在这里插入图片描述
在这里插入图片描述

  • 1
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 9
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值