微信小程序 获取当前位置信息

思路:

1.当用户进入页面,开始判断用户之前是否授权;
2.如果已授权 直接获取位置信息;反之,弹框要求用户授权,
3.当用户点击确定 进入小程序授权设置界面 打开位置权限,
4.授权方法 必须写到onShow 中(便于实时监测用户是否关闭位置权限)

实现方法

 onShow() {
    //检测用户是否之前授权
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.userLocation']) {
          wx.authorize({
            scope: 'scope.userLocation',
            success() {},
            fail() {
              wx.showModal({
                title: '小程序要获取你的地理位置',
                content: '你的位置信息将用于小程序位置接口的效果展示',
                success(res) {
                  if (res.confirm) {
                    wx.openSetting({
                      success() {
                        wx.getLocation({
                          type: 'wgs84',
                          success(res3) {
                            console.log(res3)
                          }
                        })
                      }
                    })
                  }
                }
              })
            },
          })
        }
      }
    })
    wx.startLocationUpdate({}) //开启小程序进入前台时接收位置消息
  // 获取当前位置信息
    let that = this
    wx.getLocation({
      type: 'gcj02',
      isHighAccuracy: true,
      success(res3) {
        console.log(res3)
        that.setData({
          location: res3
        })

      }
    })
     // 打开当前位置
    wx.openLocation({
      latitude: this.data.location.latitude,
      longitude: this.data.location.longitude,
      scale: 18
    })
  // 选择位置
    wx.chooseLocation({
      latitude: this.data.location.latitude,
      longitude: this.data.location.longitude,
      success(res) {
        console.log(res)
      },
    })
  },
  
  },
//   app.json 添加
 "permission": {
    "scope.userLocation": {
      "desc": "你的位置信息将用于小程序位置"
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值