forked from zhouruizhe/gmTouringMiniApp
59 lines
1.6 KiB
TypeScript
59 lines
1.6 KiB
TypeScript
import type { GeoPoint } from '@/domain/poi'
|
|||
|
|
import { defineStore } from 'pinia'
|
||
|
|
|
||
|
|
export type UserLocationStatus = 'idle' | 'locating' | 'ready' | 'denied' | 'unavailable' | 'error'
|
||
|
|
|
||
|
|
export interface UserLocationSnapshot extends GeoPoint {
|
||
|
|
accuracy: number | null
|
||
|
|
capturedAt: string
|
||
|
|
coordinateSystem: 'GCJ02'
|
||
|
|
}
|
||
|
|
|
||
|
|
interface UserLocationState {
|
||
|
|
status: UserLocationStatus
|
||
|
|
snapshot: UserLocationSnapshot | null
|
||
|
|
errorMessage: string
|
||
|
|
}
|
||
|
|
|
||
|
|
function isValidCoordinate(longitude: number, latitude: number): boolean {
|
||
|
|
return Number.isFinite(longitude)
|
||
|
|
&& Number.isFinite(latitude)
|
||
|
|
&& longitude >= -180
|
||
|
|
&& longitude <= 180
|
||
|
|
&& latitude >= -90
|
||
|
|
&& latitude <= 90
|
||
|
|
}
|
||
|
|
|
||
|
|
export const useLocationStore = defineStore('user-location-session', {
|
||
|
|
state: (): UserLocationState => ({
|
||
|
|
status: 'idle',
|
||
|
|
snapshot: null,
|
||
|
|
errorMessage: '',
|
||
|
|
}),
|
||
|
|
actions: {
|
||
|
|
startLocating() {
|
||
|
|
this.status = 'locating'
|
||
|
|
this.errorMessage = ''
|
||
|
|
},
|
||
|
|
updateLocation(longitude: number, latitude: number, accuracy?: number | null) {
|
||
|
|
if (!isValidCoordinate(longitude, latitude))
|
||
|
|
return false
|
||
|
|
|
||
|
|
this.snapshot = {
|
||
|
|
longitude,
|
||
|
|
latitude,
|
||
|
|
accuracy: Number.isFinite(accuracy) && Number(accuracy) >= 0 ? Number(accuracy) : null,
|
||
|
|
capturedAt: new Date().toISOString(),
|
||
|
|
coordinateSystem: 'GCJ02',
|
||
|
|
}
|
||
|
|
this.status = 'ready'
|
||
|
|
this.errorMessage = ''
|
||
|
|
return true
|
||
|
|
},
|
||
|
|
failLocation(status: Exclude<UserLocationStatus, 'idle' | 'locating' | 'ready'>, message: string) {
|
||
|
|
this.status = status
|
||
|
|
this.errorMessage = message
|
||
|
|
},
|
||
|
|
},
|
||
|
|
})
|