uniapp中位置授权提示

517 阅读1分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第11天,点击查看活动详情

前言

因项目的需求,需要,首次登录小程序的用户,一进来就显示一个弹窗 (允许当前小程序获取你的位置),提示

下面的图片是 点击允许后打印的结果

​ 

官网地址     uni.getSetting   获取用户的当前设置。

出现弹窗的原因是因为使用 了 uni.authorize 这个属性 

还需要在  manifest.json 中配置

总代码 

在methods中      

 isGetLocation(a = "scope.userLocation") { //检查当前是否已经授权访问scope属性
        var _this = this;
        uni.getSetting({
          success(res) {
            console.log(res)
            if (!res.authSetting[a]) { //每次进入程序判断当前是否获得授权,如果没有就去获得授权,如果获得授权,就直接获取当前地理位置
              _this.getAuthorizeInfo()
            } else {
              _this.getLocation();      
            }
          }
        });
      },
      getAuthorizeInfo(a = "scope.userLocation") { // uniapp弹窗弹出获取授权(地理,个人微信信息等授权信息)弹窗
        var _this = this;
        uni.authorize({
          scope: a,
          success() { //允许授权
            _this.getLocation();   
          }
        })
      },
      getLocation() {
        uni.getLocation({
          type: 'gcj02',
          geocode: true,
          success: res => {
            this.latitude = res.latitude
            this.longitude = res.longitude
            let latlng = [this.latitude, this.longitude]
            console.log('当前位置的经纬度', latlng);
            // console.log(res, '位置信息打印查看结果');
          },
          address: (res) => {
            console.log('address', res);
          }
        });
      },

onShow() {
      this.getLocation()
    },
    
    onload(){
      this.isGetLocation();
      
    }