微信小程序新版获取系统信息实现定位

445 阅读1分钟

image.png 从官网上这个api已经不支持了 目前网上搜索到的代码都是这个api的,现在重新写下这块的功能逻辑吧

1: wx.getSystemSetting()

image.png

// 获取是否开启了地理位置
    const systemSetting = wx.getSystemSetting();
    console.log(systemSetting.locationEnabled);
    if (systemSetting.locationEnabled) {
    }

2: wx.getAppAuthorizeSetting()

image.png

if (appAuthorizeSetting.locationAuthorized == 'denied') {
        //获取失败的处理,我这边的处理就是引导用户跳转到设置页面进行修改
         wx.openAppAuthorizeSetting({
      success(res) {
        console.log(res)
      },
      fail(res) {
        wx.showToast({
          title: res.errMsg,
          icon: 'none'
        })
      }
    })
      } else {
      // 接下来就可以正式的开始获取用户的位置了
}

3: wx.getLocation

image.png

wx.getLocation({
          type: 'gcj02', // 返回可以用于 wx.openLocation 的经纬度
          success: (res) => {
            console.log(res.longitude, res.latitude, 'res');
            getApp().globalData.longitude = res.longitude;
            getApp().globalData.latitude = res.latitude;
            // 计算用户点位距离指定点位的距离
            let data = this.data.TabControlData;
            data.forEach((item) => {
              item.distance = Math.round(this.getDistance(res.latitude, res.longitude, item.latitude, item.longitude));
            })
          },
          fail: (res) => {
            console.log(res);
            this.setData({
              Getlocation: true
            })
            this.callword('您已拒绝位置授权');
          }
        });

4:完整代码

loactionStus: function () {
    // 获取是否开启了地理位置
    const systemSetting = wx.getSystemSetting();
    console.log(systemSetting.locationEnabled);
    if (systemSetting.locationEnabled) {
      const appAuthorizeSetting = wx.getAppAuthorizeSetting()
      console.log(appAuthorizeSetting.locationAuthorized)
      if (appAuthorizeSetting.locationAuthorized == 'denied') {
 wx.openAppAuthorizeSetting({
      success(res) {
        console.log(res)
      },
      fail(res) {
        wx.showToast({
          title: res.errMsg,
          icon: 'none'
        })
      }
    })
      } else {
        wx.getLocation({
          type: 'gcj02', // 返回可以用于 wx.openLocation 的经纬度
          success: (res) => {
            console.log(res.longitude, res.latitude, 'res');
          },
          fail: (res) => {
            console.log(res);
            this.callword('您已拒绝位置授权');
          }
        });
      }
    } else {
      this.callword('定位服务未开启')
    }
  }