getpos.js 2.96 KB
// components/userinfo/getpos.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    hasFailPop:{//授权失败是否弹框
      type:Boolean,
      value:false,
    },
  },

  /**
   * 组件的初始数据
   */
  data: {},
  attached(){
  },
  /**
   * 组件的方法列表
   */
  methods: {
    getPosDo(timeout=3000){
      //timeout=0
      return new Promise(function(success,fail){
        let timer1=setTimeout(()=>{
          fail('timeout')
        },timeout)
        wx.getLocation({
          type: 'gcj02',
          success: (res) => {
            getApp().location = res
            success(res)
          },
          fail: (res) => {
            fail(res)
          },
          complete: () => {
            if (timer1) clearTimeout(timer1)
          }
        });
      })
    },
    getPos(fouce=false){
      wx.getSetting({
        success: res => {
          console.log('getPos.scope.userLocation',res.authSetting)
          let timeout=3000;
          if(typeof res.authSetting['scope.userLocation']=='undefined'){
            timeout=86400;
          }
          if(res.authSetting['scope.userLocation']===false){
            if(fouce || this.data.hasFailPop){
              this.selectComponent('#confirm').options({
                header: '定位失败',
                body: '请开启定位,为您查询附近餐厅。'
              }).show();
            }else{
              this.triggerEvent("pos",{
                latitude: '',
                longitude: '',
              });
            }
          }else{//
            console.log('getApp().location',getApp().location)
            if(getApp().location && getApp().location.latitude){
              return this.triggerEvent("pos",{
                latitude: getApp().location.latitude,
                longitude: getApp().location.longitude,
              });
            }
            this.getPosDo(timeout).then(res=>{
              console.log('getPos.then',res)
              this.triggerEvent("pos",{
                latitude: res.latitude,
                longitude: res.longitude,
              });
            }).catch(res=>{
              console.log('getPos.catch',res)
              if(this.data.hasFailPop){
                if ('getLocation:fail auth deny' == res.errMsg
                  || 'getLocation:fail:auth denied' == res.errMsg
                  || 'getLocation:fail authorize no response' == res.errMsg) {
                  this.selectComponent('#confirm').options({
                    header: '定位失败',
                    body: '请开启定位,为您查询附近餐厅。'
                  }).show();
                }
              }
              this.triggerEvent("pos",{
                latitude: '',
                longitude: '',
              });
            })
          }
        }
      })
    },
    confirmEvent(e){
      wx.openSetting({
        success:res=>{
          console.log('getPos.openSetting',res)
          this.getPos();
        }
      })
    },
  }
})