-
-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
index.ts
87 lines (74 loc) · 2.07 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/* this implementation is original ported from https://github.com/logaretm/vue-use-web by Abdelrahman Awad */
import type { Ref } from 'vue-demi'
import type { ConfigurableNavigator } from '../_configurable'
import { tryOnScopeDispose } from '@vueuse/shared'
import { ref, shallowRef } from 'vue-demi'
import { defaultNavigator } from '../_configurable'
import { useSupported } from '../useSupported'
export interface UseGeolocationOptions extends Partial<PositionOptions>, ConfigurableNavigator {
immediate?: boolean
}
/**
* Reactive Geolocation API.
*
* @see https://vueuse.org/useGeolocation
* @param options
*/
export function useGeolocation(options: UseGeolocationOptions = {}) {
const {
enableHighAccuracy = true,
maximumAge = 30000,
timeout = 27000,
navigator = defaultNavigator,
immediate = true,
} = options
const isSupported = useSupported(() => navigator && 'geolocation' in navigator)
const locatedAt: Ref<number | null> = ref(null)
const error = shallowRef<GeolocationPositionError | null>(null)
const coords: Ref<Omit<GeolocationPosition['coords'], 'toJSON'>> = ref({
accuracy: 0,
latitude: Number.POSITIVE_INFINITY,
longitude: Number.POSITIVE_INFINITY,
altitude: null,
altitudeAccuracy: null,
heading: null,
speed: null,
})
function updatePosition(position: GeolocationPosition) {
locatedAt.value = position.timestamp
coords.value = position.coords
error.value = null
}
let watcher: number
function resume() {
if (isSupported.value) {
watcher = navigator!.geolocation.watchPosition(
updatePosition,
err => error.value = err,
{
enableHighAccuracy,
maximumAge,
timeout,
},
)
}
}
if (immediate)
resume()
function pause() {
if (watcher && navigator)
navigator.geolocation.clearWatch(watcher)
}
tryOnScopeDispose(() => {
pause()
})
return {
isSupported,
coords,
locatedAt,
error,
resume,
pause,
}
}
export type UseGeolocationReturn = ReturnType<typeof useGeolocation>