美文网首页
小程序位置授权弹窗方法封装

小程序位置授权弹窗方法封装

作者: 子绎 | 来源:发表于2020-04-22 11:44 被阅读0次

    在小程序中,不管是地图还是获取位置信息,都首先需要获得用户的位置许可授权。

    而为了确保在调用一些其他方法的时候已经提前获取到用户位置授权,就必须在操作其他步骤之前,先强制获得用户位置授权。不然往下的业务逻辑也没法继续。

    封装方法,调用此方法时,能够引导用户进行授权,如果用户没有授权,将会跳转到手动授权页面

     getUserCity(fn,type){
        wx.getLocation({
          type: type?type:'wgs84',
          success :(res)=> {
            const latitude = res.latitude
            const longitude = res.longitude
            const speed = res.speed
            const accuracy = res.accuracy
            fn(res)
          },
          fail(ress){
            // 检查授权
            wx.getSetting({
              success: (res) => {
                // console.log(res.authSetting);
                //已授权就是true
                if (res.authSetting['scope.userLocation']) {
                  this.getUserPosition((res, flag) => {
                    // console.log(res, flag);
                    if (flag.flag) {
                      fn(res)
                    }
                  });
                } else {
                  //如果未授权  打开弹窗
                  wx.showModal({
                    title: '请授权位置权限',
                    showCancel: false,
                    cancelColor: 'cancelColor',
                    success: () => {
                      wx.openSetting({
                        complete: (res) => {},
                      })
                    }
                  })
                }
              }
            })
          }
         })
      },
    

    方法调用

      两个参数,第一个参数是一个函数回调 
    第二个参数是传入获取的经纬度类型 分为wgs84和gcj02  一种是给百度地图 高德地图等使用 一种是给小程序内部地图使用
            app.getUserCity((res)=>{
                console.log(res)
                res会返回已经获取到的经纬度
                  })
            },'gcj02')
    

    效果

    image.png image.png
    image.png

    相关文章

      网友评论

          本文标题:小程序位置授权弹窗方法封装

          本文链接:https://www.haomeiwen.com/subject/cnobihtx.html