06.Taro框架获取用户地址位置解决方案
环境信息
1.小程序框架: Taro
- Taro 版本:3.4.0
设计流程图
核心代码
import Taro from "[@tarojs](/user/tarojs)/taro";
// TODO 自己实现的 store
import store from '@/utils/store';
// TARO.env
import { PLATFORM_TYPE } from '@/constant/index';
const locationEntity: TaroMiniApp.IUtilsLocationEntity = {
checkLocation: () => {
return Taro.getSetting()
.then((res: Taro.getSetting.SuccessCallbackResult) => {
return Promise.resolve(res.authSetting['scope.userLocation'])
}).catch((err: TaroGeneral.CallbackResult) => {
throw Promise.reject(err);
})
},
authLocation: async () => {
try {
const settingRes: Taro.getSetting.SuccessCallbackResult = await Taro.getSetting();
const firstAuth = 'scope.userLocation' in settingRes.authSetting;
// 第一次授权
if (!firstAuth) {
const uerLocationRes: TaroMiniApp.IUtilsLocationEntity.TLocationCallbackResult = await locationEntity.getUserLocation();
return uerLocationRes;
}
// 未授权
if (!settingRes.authSetting['scope.userLocation']) {
const modalRes: Taro.showModal.SuccessCallbackResult = await Taro.showModal({
title: '提示',
content: '您未授权定位权限,无法获取您的定位',
cancelText: '取消',
confirmText: '去设置',
confirmColor: '#ff5500',
});
if (modalRes.confirm) {
// 进入设置类别
const openSettingRes = await Taro.openSetting();
console.log(openSettingRes)
const uerAuthLocationRes: TaroMiniApp.IUtilsLocationEntity.TLocationCallbackResult = await locationEntity.getUserLocation();
return uerAuthLocationRes;
}
return {
errMsg: "getLocation:fail auth deny"
}
}
return {
errMsg: "getLocation:ok"
}
} catch (error) {
console.log('err:', error);
throw error;
}
},
// 获取用户定位
getUserLocation: async (realTime: boolean = false) => {
try {
// 非实时
if (!realTime && store.get('USER_LOCATION')) {
return store.get('USER_LOCATION');
}
const userLocationRes: Taro.getLocation.SuccessCallbackResult = await Taro.getLocation({ type: 'gcj02' })
if (PLATFORM_TYPE === 'WEAPP') {
if (userLocationRes?.errMsg.indexOf('ok') !== -1) {
store.set('USER_LOCATION', userLocationRes, false);
}
}
if (PLATFORM_TYPE === 'ALIPAY') {
store.set('USER_LOCATION', userLocationRes, false);
}
console.log("userLocationRes:", userLocationRes);
return userLocationRes;
} catch (error) {
throw error;
}
},
// 一键式授权
autoAuth: async () => {
try {
const checkAuth: any = await locationEntity.checkLocation();
if (!checkAuth) {
const res = await locationEntity.authLocation();
return res;
}
return await locationEntity.getUserLocation();
} catch (error) {
throw error;
}
}
}
export default locationEntity;
核心逻辑
- 第一次定位授权的判断,通过 in 运算符的