@tplc/business
Version:
95 lines (91 loc) • 3.21 kB
text/typescript
import { useTranslate } from '@tplc/wot'
import { ref } from 'vue'
import { getUserLocation, UserLocation } from './useLocation.api'
export const currentLocation = ref<UserLocation>()
export const currentUserLatLon = ref<UniApp.GetLocationSuccess>()
const useLocation = (onLocation?: (location: UserLocation) => void) => {
const { translate } = useTranslate()
// 正在获取经纬度
const locationIng = ref(false)
// 检查用户是否授权定位
async function checkLocationPermission() {
// #ifdef MP-WEIXIN
try {
const res = await uni.getSetting()
return res.authSetting['scope.userLocation']
} catch (err) {
return false
}
// #endif
}
// 引导用户前往设置页面重新授权
function navigateToSettings(forceSetting = false) {
/** 48小时提醒一次 */
const lastTime = uni.getStorageSync('location_last_time')
if (lastTime && new Date().getTime() - lastTime < 48 * 60 * 60 * 1000 && !forceSetting) {
return
}
uni.setStorageSync('location_last_time', new Date().getTime())
uni.showModal({
title: translate('定位权限申请'),
content: translate('您尚未开启定位权限,无法正常使用该功能,请前往设置页面开启。'),
success: function (res) {
if (res.confirm) {
uni.openSetting({
success: function (setting) {
if (setting.authSetting['scope.userLocation'] === 'authorized') {
// 重新尝试获取位置信息
getLocation()
} else {
uni.showToast({ title: translate('请在设置中开启定位权限'), icon: 'none' })
}
},
})
}
},
})
}
const getLocation = async (force = false, forceSetting = false) => {
// 如果不是force并且当前位置有值,则不刷新
if (!force && currentLocation.value) return
if ((await checkLocationPermission()) !== false) {
locationIng.value = true
await new Promise<void>((resolve) => {
uni.getLocation({
type: 'gcj02',
// type: 'wgs84',
success: function (res) {
currentUserLatLon.value = res
getUserLocation({
userLongitude: res.longitude.toString(),
userLatitude: res.latitude.toString(),
})
.then((res) => {
currentLocation.value = res.data
if (force) onLocation?.(res.data)
})
.finally(() => {
locationIng.value = false
resolve()
})
},
fail: function (res) {
console.log('获取位置信息失败:', res)
getUserLocation()
.then((res) => {
currentLocation.value = res.data
})
.finally(() => {
locationIng.value = false
resolve()
})
},
})
})
} else {
navigateToSettings(forceSetting)
}
}
return { getLocation, locationIng, userLocation: currentLocation, userLatLon: currentUserLatLon }
}
export default useLocation