|
| 1 | +export interface Coordinates { |
| 2 | + latitude: number; |
| 3 | + longitude: number; |
| 4 | + accuracy?: number; |
| 5 | + altitude?: number | null; |
| 6 | + heading?: number | null; |
| 7 | + speed?: number | null; |
| 8 | + timestamp: number; |
| 9 | +} |
| 10 | + |
| 11 | +export interface LocationOptions { |
| 12 | + enableHighAccuracy?: boolean; |
| 13 | + timeout?: number; |
| 14 | + maximumAge?: number; |
| 15 | +} |
| 16 | + |
| 17 | +/** |
| 18 | + * Get current geolocation from user's device. |
| 19 | + */ |
| 20 | +export function getCurrentLocation(options?: LocationOptions): Promise<Coordinates> { |
| 21 | + return new Promise((resolve, reject) => { |
| 22 | + if (!navigator.geolocation) { |
| 23 | + return reject(new Error("Geolocation is not supported by this browser.")); |
| 24 | + } |
| 25 | + |
| 26 | + navigator.geolocation.getCurrentPosition( |
| 27 | + (pos) => { |
| 28 | + const coords = pos.coords; |
| 29 | + resolve({ |
| 30 | + latitude: coords.latitude, |
| 31 | + longitude: coords.longitude, |
| 32 | + accuracy: coords.accuracy, |
| 33 | + altitude: coords.altitude, |
| 34 | + heading: coords.heading, |
| 35 | + speed: coords.speed, |
| 36 | + timestamp: pos.timestamp |
| 37 | + }); |
| 38 | + }, |
| 39 | + (err) => reject(err), |
| 40 | + options |
| 41 | + ); |
| 42 | + }); |
| 43 | +} |
| 44 | + |
| 45 | +/** |
| 46 | + * Continuously track user location. |
| 47 | + * @returns Watch ID to use with clearLocationWatch() |
| 48 | + */ |
| 49 | +export function watchLocation( |
| 50 | + callback: (location: Coordinates) => void, |
| 51 | + errorCallback?: (error: GeolocationPositionError) => void, |
| 52 | + options?: LocationOptions |
| 53 | +): number { |
| 54 | + return navigator.geolocation.watchPosition( |
| 55 | + (pos) => { |
| 56 | + const coords = pos.coords; |
| 57 | + callback({ |
| 58 | + latitude: coords.latitude, |
| 59 | + longitude: coords.longitude, |
| 60 | + accuracy: coords.accuracy, |
| 61 | + altitude: coords.altitude, |
| 62 | + heading: coords.heading, |
| 63 | + speed: coords.speed, |
| 64 | + timestamp: pos.timestamp |
| 65 | + }); |
| 66 | + }, |
| 67 | + errorCallback ?? (() => {}), |
| 68 | + options |
| 69 | + ); |
| 70 | +} |
| 71 | + |
| 72 | +/** |
| 73 | + * Clear a location watch using its ID. |
| 74 | + */ |
| 75 | +export function clearLocationWatch(id: number): void { |
| 76 | + navigator.geolocation.clearWatch(id); |
| 77 | +} |
0 commit comments