Skip to content

Commit 5d3a963

Browse files
Merge pull request #3 from aboutbits/location-provider
Location provider
2 parents b7a0915 + 7a1f406 commit 5d3a963

3 files changed

Lines changed: 79 additions & 1 deletion

File tree

src/index.ts

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,18 @@
11
import { useInterval } from './useInterval/useInterval'
22
import { AsyncState, getAsyncState } from './async-data/asyncState'
33
import { AsyncView } from './async-data/AsyncView'
4+
import {
5+
LocationProvider,
6+
LocationContext,
7+
LocationContextValue,
8+
} from './location-provider/LocationProvider'
49

5-
export { useInterval, AsyncState, getAsyncState, AsyncView }
10+
export {
11+
useInterval,
12+
AsyncState,
13+
getAsyncState,
14+
AsyncView,
15+
LocationProvider,
16+
LocationContext,
17+
LocationContextValue,
18+
}
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import React, { useEffect, useState } from 'react'
2+
import { createContext } from 'react'
3+
import { useInterval } from '../index'
4+
import { getCurrentLocation } from './getCurrentLocation'
5+
6+
export type LocationContextValue = {
7+
location: GeolocationPosition | null
8+
}
9+
10+
export const LocationContext = createContext<LocationContextValue>({
11+
location: null,
12+
})
13+
14+
export const LocationProvider: React.FC<{
15+
highAccuracy: boolean
16+
delay: number
17+
}> = ({ highAccuracy, delay, children }) => {
18+
const [location, setLocation] = useState<LocationContextValue>({
19+
location: null,
20+
})
21+
22+
const updateLocation = async () => {
23+
const position = await getCurrentLocation(highAccuracy).catch(
24+
() => location.location
25+
)
26+
setLocation({ location: position })
27+
}
28+
29+
useEffect(() => {
30+
updateLocation()
31+
}, [])
32+
33+
useInterval(() => {
34+
updateLocation()
35+
}, delay)
36+
37+
return (
38+
<LocationContext.Provider value={location}>
39+
{children}
40+
</LocationContext.Provider>
41+
)
42+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
const getCurrentLocation = (
2+
highAccuracy = false
3+
): Promise<GeolocationPosition> => {
4+
return new Promise<GeolocationPosition>((resolve, reject) => {
5+
const successCallback = (position: GeolocationPosition): void => {
6+
resolve(position)
7+
}
8+
9+
const errorCallback = (error: GeolocationPositionError) => {
10+
reject(error.message)
11+
}
12+
13+
if (navigator.geolocation) {
14+
navigator.geolocation.getCurrentPosition(successCallback, errorCallback, {
15+
enableHighAccuracy: highAccuracy,
16+
})
17+
} else {
18+
reject('Geolocation not supported')
19+
}
20+
})
21+
}
22+
23+
export { getCurrentLocation }

0 commit comments

Comments
 (0)