小程序-地理位置授权,取消-重新授权,方法封装

1,236 阅读2分钟
产品功能截图如下:

image.png

简要描述:
每次进入程序通过调用uni.getSetting接口判断当前是否获得授权,要求用户进行授权,调用authorize判断用户是什么操作,用户【允许】则getLocation获取地理位置;用户【拒绝】则给出弹框提示。再次进入页面,也给出弹框提示,用户可以关闭或者同意后openSetting弹出授权界面。
import store from '../store'
import amapFile from './amap-wx.js'
import {GD_KEY} from './constant'

  // 1. 检查当前是否已经授权访问scope属性
  const storeInfo = store.state.currentShippingAddrInfo.storeInfo
  export const isGetLocation = ()=> {     
    return new Promise((resolve,reject)=>{
      uni.getSetting({
        success:async(res)=> {       
          //1.1 每次进入程序判断当前是否获得授权,
          // 如果没有就去获得授权,如果获得授权,就直接获取当前地理位置         
          if (!res.authSetting["scope.userLocation"]) {   
            try {
              await getAuth()
              const resdata = await getLocationFn()
              await getSroreAddress(resdata)
              await resolve() 
            } catch (error) {
              reject()
            }
           
          } else {
            const resdata =await getLocationFn()
            await getSroreAddress(resdata)
            await resolve() 

          }
        }
      });
    })

  }
  function getAuth(){
    return new Promise((resolve,reject)=>{
      uni.authorize({
        scope: 'scope.userLocation',
        // 允许授权
        success: async()=> {
          resolve()
        },
        // 拒绝授权 如果没有storeId或者chainId则授权地理位置 
        fail() {
          reject('拒绝了授权')        
        }
      }) 
    })
  }
  //  获取用户的地理位置,
  export function getLocationFn() {
    return new Promise((resolve,reject)=>{
      uni.getLocation({
        type: 'gcj02', // <map> 组件默认为国测局坐标gcj02
        geocode:true,
        success: async(res)=> {
          resolve(res) 
        },
        fail: function() {
          getLocationFail()
        }
      })
    })
  }

  //获取位置失败
 export function getLocationFail() {
    uni.showModal({
      title: '地理位置未授权',
      content: '如需正常使用,请点击确认并在设置页允许"使用我的地理位置"',
      confirmText: '确认',
      success: function(res) {
        if (res.confirm) {
          //打开小程序设置页面
          uni.openSetting({
            success(resSetting) {
              console.log('authSettingres',resSetting)      
            }
          });
        }
      }
    })
  }

   function setLatLnt(res){
    uni.setStorageSync('longitude', res.longitude)
    uni.setStorageSync('latitude', res.latitude);
    store.dispatch('infoInfo/setLonLat',({
      longitude: res.longitude,
      latitude: res.latitude,
      address: res.address
    }))
  }

  //解析经纬度
  export const getSroreAddress = async(res) =>{
    return new Promise((resolve,reject)=>{
      const {latitude, longitude} = res
      var myAmapFun = new amapFile.AMapWX({ key: GD_KEY});
      myAmapFun.getRegeo({
        location: `${longitude},${latitude}`, //location的格式为'经度,纬度'
        success: function (e) {
          const address = e[0].regeocodeData.addressComponent.city; //城市
          setLatLnt({
            longitude:longitude,
            latitude:latitude,
            address:address
          })
          resolve(e)

        },
        fail: function (err) {
          console.log(err);
        },
      });
    })
  }


使用如下:

image.png

import {isGetLocation,getLocationFail,getSroreAddress} from '../../common/location';

try {
  await isGetLocation();
  await this.queryList()
  this.isAuth = true
} catch (error) {
  getLocationFail()  
}
具体实现就是如上啦~
多多指教,共同成长💪