微信小程序之获取用户位置权限(拒绝后提醒)

第一步:由于有可能会多次使用定位的方法,所以我把定位的方法写到App.js中,方便调用

App({
  //获取用户地理位置权限
  getPermission: function(obj) {
    wx.chooseLocation({
      success: function(res) {
        obj.setData({
          addr: res.address //调用成功直接设置地址
        })
      },
      fail: function() {
        wx.getSetting({
          success: function(res) {
            var statu = res.authSetting;
            if (!statu['scope.userLocation']) {
              wx.showModal({
                title: '是否授权当前位置',
                content: '需要获取您的地理位置,请确认授权,否则地图功能将无法使用',
                success: function(tip) {
                  if (tip.confirm) {
                    wx.openSetting({
                      success: function(data) {
                        if (data.authSetting["scope.userLocation"] === true) {
                          wx.showToast({
                            title: '授权成功',
                            icon: 'success',
                            duration: 1000
                          })
                          //授权成功之后,再调用chooseLocation选择地方
                          wx.chooseLocation({
                            success: function(res) {
                              obj.setData({
                                addr: res.address
                              })
                              console.log(res.address)
                            },
                          })
                        } else {
                          wx.showToast({
                            title: '授权失败',
                            icon: 'success',
                            duration: 1000
                          })
                        }
                      }
                    })
                  }
                }
              })
            }
          },
          fail: function(res) {
            wx.showToast({
              title: '调用授权窗口失败',
              icon: 'success',
              duration: 1000
            })
          }
        })
      }
    })
  },
})

第二步:在需要获取地址的页面中:

var app = getApp();
Page({
   data:{
        addr:'请选择位置'         
    },
    //选择获取地理位置
    getAddress:function(){
          var that=this;
      app.getPermission(that);    //传入that值可以在app.js页面直接设置内容    
    }, 
})

 

posted @ 2018-07-23 13:53  松歌  阅读(582)  评论(0编辑  收藏  举报