@usefy/use-geolocation 0.0.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,283 @@
1
+ /**
2
+ * Geolocation coordinates data
3
+ * Note: Named GeoCoordinates to avoid conflict with native GeolocationCoordinates type
4
+ */
5
+ interface GeoCoordinates {
6
+ /** Latitude in decimal degrees */
7
+ latitude: number;
8
+ /** Longitude in decimal degrees */
9
+ longitude: number;
10
+ /** Altitude in meters above the WGS 84 ellipsoid (null if unavailable) */
11
+ altitude: number | null;
12
+ /** Accuracy of latitude/longitude in meters */
13
+ accuracy: number;
14
+ /** Accuracy of altitude in meters (null if unavailable) */
15
+ altitudeAccuracy: number | null;
16
+ /** Direction of travel in degrees (0-360, null if unavailable) */
17
+ heading: number | null;
18
+ /** Speed in meters per second (null if unavailable) */
19
+ speed: number | null;
20
+ }
21
+ /**
22
+ * Position data with timestamp
23
+ * Note: Named GeoPosition to avoid conflict with native GeolocationPosition type
24
+ */
25
+ interface GeoPosition {
26
+ /** Coordinates and related data */
27
+ coords: GeoCoordinates;
28
+ /** Timestamp when position was acquired */
29
+ timestamp: number;
30
+ }
31
+ /**
32
+ * Geolocation error types
33
+ */
34
+ type GeolocationErrorCode = "PERMISSION_DENIED" | "POSITION_UNAVAILABLE" | "TIMEOUT" | "NOT_SUPPORTED";
35
+ /**
36
+ * Custom error object for geolocation failures
37
+ */
38
+ interface GeolocationError {
39
+ /** Error code */
40
+ code: GeolocationErrorCode;
41
+ /** Human-readable error message */
42
+ message: string;
43
+ /** Original native error (if available) */
44
+ nativeError?: GeolocationPositionError;
45
+ }
46
+ /**
47
+ * Permission state for geolocation
48
+ */
49
+ type PermissionState = "prompt" | "granted" | "denied" | "unavailable";
50
+ /**
51
+ * Options for useGeolocation hook
52
+ */
53
+ interface UseGeolocationOptions {
54
+ /**
55
+ * Enable high accuracy mode (uses GPS instead of network)
56
+ * WARNING: High accuracy mode may consume more battery power
57
+ * @default false
58
+ */
59
+ enableHighAccuracy?: boolean;
60
+ /**
61
+ * Maximum age of cached position in milliseconds
62
+ * Set to 0 to always request fresh position
63
+ * @default 0
64
+ */
65
+ maximumAge?: number;
66
+ /**
67
+ * Timeout in milliseconds for position request
68
+ * @default 30000 (30 seconds)
69
+ */
70
+ timeout?: number;
71
+ /**
72
+ * Start watching position immediately on mount
73
+ * When true, automatically starts continuous position tracking
74
+ * @default false
75
+ */
76
+ watch?: boolean;
77
+ /**
78
+ * Get initial position immediately on mount
79
+ * When true, automatically fetches position once on mount
80
+ * @default true
81
+ */
82
+ immediate?: boolean;
83
+ /**
84
+ * Callback when position is successfully retrieved
85
+ * @param position - The geolocation position data
86
+ */
87
+ onSuccess?: (position: GeoPosition) => void;
88
+ /**
89
+ * Callback when an error occurs
90
+ * @param error - The geolocation error
91
+ */
92
+ onError?: (error: GeolocationError) => void;
93
+ /**
94
+ * Callback when position changes (during watch mode)
95
+ * @param position - The updated geolocation position data
96
+ */
97
+ onPositionChange?: (position: GeoPosition) => void;
98
+ /**
99
+ * Callback when permission state changes
100
+ * @param state - The new permission state
101
+ */
102
+ onPermissionChange?: (state: PermissionState) => void;
103
+ }
104
+ /**
105
+ * Return type for useGeolocation hook
106
+ */
107
+ interface UseGeolocationReturn {
108
+ /** Current position data (null if not yet retrieved) */
109
+ position: GeoPosition | null;
110
+ /** Loading state (true while fetching position) */
111
+ loading: boolean;
112
+ /** Error object (null if no error) */
113
+ error: GeolocationError | null;
114
+ /** Current permission state */
115
+ permission: PermissionState;
116
+ /** Whether geolocation is supported in this environment */
117
+ isSupported: boolean;
118
+ /**
119
+ * Manually get current position (one-time request)
120
+ */
121
+ getCurrentPosition: () => void;
122
+ /**
123
+ * Start watching position for real-time updates
124
+ */
125
+ watchPosition: () => void;
126
+ /**
127
+ * Stop watching position
128
+ */
129
+ clearWatch: () => void;
130
+ /**
131
+ * Calculate distance from current position to target coordinates in meters
132
+ * Uses Haversine formula (assumes spherical Earth, ~0.5% error margin)
133
+ * @param latitude - Target latitude in decimal degrees
134
+ * @param longitude - Target longitude in decimal degrees
135
+ * @returns Distance in meters, or null if position unavailable
136
+ */
137
+ distanceFrom: (latitude: number, longitude: number) => number | null;
138
+ /**
139
+ * Calculate bearing/direction from current position to target coordinates
140
+ * @param latitude - Target latitude in decimal degrees
141
+ * @param longitude - Target longitude in decimal degrees
142
+ * @returns Bearing in degrees (0-360, where 0=North, 90=East, 180=South, 270=West), or null if position unavailable
143
+ */
144
+ bearingTo: (latitude: number, longitude: number) => number | null;
145
+ }
146
+
147
+ /**
148
+ * A React hook for accessing device geolocation with real-time tracking and distance calculation.
149
+ *
150
+ * Features:
151
+ * - Get current position (one-time)
152
+ * - Watch position for real-time updates
153
+ * - Permission state tracking
154
+ * - Distance calculation using Haversine formula
155
+ * - Bearing/direction calculation
156
+ * - SSR compatible
157
+ * - TypeScript support
158
+ *
159
+ * @param options - Configuration options
160
+ * @returns Geolocation state and control functions
161
+ *
162
+ * @example
163
+ * ```tsx
164
+ * // Basic usage - get current position
165
+ * function MyLocation() {
166
+ * const { position, loading, error } = useGeolocation();
167
+ *
168
+ * if (loading) return <p>Loading location...</p>;
169
+ * if (error) return <p>Error: {error.message}</p>;
170
+ * if (!position) return <p>No position yet</p>;
171
+ *
172
+ * return (
173
+ * <div>
174
+ * <p>Latitude: {position.coords.latitude}</p>
175
+ * <p>Longitude: {position.coords.longitude}</p>
176
+ * <p>Accuracy: {position.coords.accuracy}m</p>
177
+ * </div>
178
+ * );
179
+ * }
180
+ * ```
181
+ *
182
+ * @example
183
+ * ```tsx
184
+ * // Real-time tracking with watch
185
+ * function LiveTracking() {
186
+ * const { position, watchPosition, clearWatch } = useGeolocation({
187
+ * immediate: false,
188
+ * watch: false,
189
+ * });
190
+ *
191
+ * return (
192
+ * <div>
193
+ * <button onClick={watchPosition}>Start Tracking</button>
194
+ * <button onClick={clearWatch}>Stop Tracking</button>
195
+ * {position && (
196
+ * <p>Current: {position.coords.latitude}, {position.coords.longitude}</p>
197
+ * )}
198
+ * </div>
199
+ * );
200
+ * }
201
+ * ```
202
+ *
203
+ * @example
204
+ * ```tsx
205
+ * // Distance calculation
206
+ * function DistanceToDestination() {
207
+ * const { position, distanceFrom } = useGeolocation();
208
+ *
209
+ * // New York City coordinates
210
+ * const nyLat = 40.7128;
211
+ * const nyLon = -74.0060;
212
+ *
213
+ * const distance = distanceFrom(nyLat, nyLon);
214
+ *
215
+ * return (
216
+ * <div>
217
+ * {distance && (
218
+ * <p>Distance to NYC: {(distance / 1000).toFixed(2)} km</p>
219
+ * )}
220
+ * </div>
221
+ * );
222
+ * }
223
+ * ```
224
+ *
225
+ * @example
226
+ * ```tsx
227
+ * // With callbacks and high accuracy
228
+ * const geolocation = useGeolocation({
229
+ * enableHighAccuracy: true,
230
+ * timeout: 10000,
231
+ * onSuccess: (pos) => console.log('Got position:', pos),
232
+ * onError: (err) => console.error('Geolocation error:', err),
233
+ * onPositionChange: (pos) => console.log('Position updated:', pos),
234
+ * onPermissionChange: (state) => console.log('Permission:', state),
235
+ * });
236
+ * ```
237
+ */
238
+ declare function useGeolocation(options?: UseGeolocationOptions): UseGeolocationReturn;
239
+
240
+ /**
241
+ * Calculate distance between two points using Haversine formula
242
+ *
243
+ * The Haversine formula determines the great-circle distance between two points
244
+ * on a sphere given their longitudes and latitudes. This assumes a spherical Earth,
245
+ * which introduces an error of up to 0.5% compared to more accurate ellipsoidal models.
246
+ *
247
+ * @param lat1 - Latitude of first point in decimal degrees
248
+ * @param lon1 - Longitude of first point in decimal degrees
249
+ * @param lat2 - Latitude of second point in decimal degrees
250
+ * @param lon2 - Longitude of second point in decimal degrees
251
+ * @returns Distance in meters
252
+ *
253
+ * @example
254
+ * ```typescript
255
+ * // Distance from San Francisco to Los Angeles
256
+ * const distance = haversineDistance(37.7749, -122.4194, 34.0522, -118.2437);
257
+ * console.log(distance); // ~559,000 meters (559 km)
258
+ * ```
259
+ */
260
+ declare function haversineDistance(lat1: number, lon1: number, lat2: number, lon2: number): number;
261
+ /**
262
+ * Calculate initial bearing (forward azimuth) from point 1 to point 2
263
+ *
264
+ * The bearing is the direction you would need to travel from the first point
265
+ * to reach the second point along a great circle path. Note that the bearing
266
+ * may change along the path (except when traveling due north/south or along the equator).
267
+ *
268
+ * @param lat1 - Latitude of first point in decimal degrees
269
+ * @param lon1 - Longitude of first point in decimal degrees
270
+ * @param lat2 - Latitude of second point in decimal degrees
271
+ * @param lon2 - Longitude of second point in decimal degrees
272
+ * @returns Bearing in degrees (0-360, where 0=North, 90=East, 180=South, 270=West)
273
+ *
274
+ * @example
275
+ * ```typescript
276
+ * // Bearing from New York to London
277
+ * const bearing = calculateBearing(40.7128, -74.0060, 51.5074, -0.1278);
278
+ * console.log(bearing); // ~51 degrees (Northeast)
279
+ * ```
280
+ */
281
+ declare function calculateBearing(lat1: number, lon1: number, lat2: number, lon2: number): number;
282
+
283
+ export { type GeoCoordinates, type GeoPosition, type GeolocationError, type GeolocationErrorCode, type PermissionState, type UseGeolocationOptions, type UseGeolocationReturn, calculateBearing, haversineDistance, useGeolocation };
@@ -0,0 +1,283 @@
1
+ /**
2
+ * Geolocation coordinates data
3
+ * Note: Named GeoCoordinates to avoid conflict with native GeolocationCoordinates type
4
+ */
5
+ interface GeoCoordinates {
6
+ /** Latitude in decimal degrees */
7
+ latitude: number;
8
+ /** Longitude in decimal degrees */
9
+ longitude: number;
10
+ /** Altitude in meters above the WGS 84 ellipsoid (null if unavailable) */
11
+ altitude: number | null;
12
+ /** Accuracy of latitude/longitude in meters */
13
+ accuracy: number;
14
+ /** Accuracy of altitude in meters (null if unavailable) */
15
+ altitudeAccuracy: number | null;
16
+ /** Direction of travel in degrees (0-360, null if unavailable) */
17
+ heading: number | null;
18
+ /** Speed in meters per second (null if unavailable) */
19
+ speed: number | null;
20
+ }
21
+ /**
22
+ * Position data with timestamp
23
+ * Note: Named GeoPosition to avoid conflict with native GeolocationPosition type
24
+ */
25
+ interface GeoPosition {
26
+ /** Coordinates and related data */
27
+ coords: GeoCoordinates;
28
+ /** Timestamp when position was acquired */
29
+ timestamp: number;
30
+ }
31
+ /**
32
+ * Geolocation error types
33
+ */
34
+ type GeolocationErrorCode = "PERMISSION_DENIED" | "POSITION_UNAVAILABLE" | "TIMEOUT" | "NOT_SUPPORTED";
35
+ /**
36
+ * Custom error object for geolocation failures
37
+ */
38
+ interface GeolocationError {
39
+ /** Error code */
40
+ code: GeolocationErrorCode;
41
+ /** Human-readable error message */
42
+ message: string;
43
+ /** Original native error (if available) */
44
+ nativeError?: GeolocationPositionError;
45
+ }
46
+ /**
47
+ * Permission state for geolocation
48
+ */
49
+ type PermissionState = "prompt" | "granted" | "denied" | "unavailable";
50
+ /**
51
+ * Options for useGeolocation hook
52
+ */
53
+ interface UseGeolocationOptions {
54
+ /**
55
+ * Enable high accuracy mode (uses GPS instead of network)
56
+ * WARNING: High accuracy mode may consume more battery power
57
+ * @default false
58
+ */
59
+ enableHighAccuracy?: boolean;
60
+ /**
61
+ * Maximum age of cached position in milliseconds
62
+ * Set to 0 to always request fresh position
63
+ * @default 0
64
+ */
65
+ maximumAge?: number;
66
+ /**
67
+ * Timeout in milliseconds for position request
68
+ * @default 30000 (30 seconds)
69
+ */
70
+ timeout?: number;
71
+ /**
72
+ * Start watching position immediately on mount
73
+ * When true, automatically starts continuous position tracking
74
+ * @default false
75
+ */
76
+ watch?: boolean;
77
+ /**
78
+ * Get initial position immediately on mount
79
+ * When true, automatically fetches position once on mount
80
+ * @default true
81
+ */
82
+ immediate?: boolean;
83
+ /**
84
+ * Callback when position is successfully retrieved
85
+ * @param position - The geolocation position data
86
+ */
87
+ onSuccess?: (position: GeoPosition) => void;
88
+ /**
89
+ * Callback when an error occurs
90
+ * @param error - The geolocation error
91
+ */
92
+ onError?: (error: GeolocationError) => void;
93
+ /**
94
+ * Callback when position changes (during watch mode)
95
+ * @param position - The updated geolocation position data
96
+ */
97
+ onPositionChange?: (position: GeoPosition) => void;
98
+ /**
99
+ * Callback when permission state changes
100
+ * @param state - The new permission state
101
+ */
102
+ onPermissionChange?: (state: PermissionState) => void;
103
+ }
104
+ /**
105
+ * Return type for useGeolocation hook
106
+ */
107
+ interface UseGeolocationReturn {
108
+ /** Current position data (null if not yet retrieved) */
109
+ position: GeoPosition | null;
110
+ /** Loading state (true while fetching position) */
111
+ loading: boolean;
112
+ /** Error object (null if no error) */
113
+ error: GeolocationError | null;
114
+ /** Current permission state */
115
+ permission: PermissionState;
116
+ /** Whether geolocation is supported in this environment */
117
+ isSupported: boolean;
118
+ /**
119
+ * Manually get current position (one-time request)
120
+ */
121
+ getCurrentPosition: () => void;
122
+ /**
123
+ * Start watching position for real-time updates
124
+ */
125
+ watchPosition: () => void;
126
+ /**
127
+ * Stop watching position
128
+ */
129
+ clearWatch: () => void;
130
+ /**
131
+ * Calculate distance from current position to target coordinates in meters
132
+ * Uses Haversine formula (assumes spherical Earth, ~0.5% error margin)
133
+ * @param latitude - Target latitude in decimal degrees
134
+ * @param longitude - Target longitude in decimal degrees
135
+ * @returns Distance in meters, or null if position unavailable
136
+ */
137
+ distanceFrom: (latitude: number, longitude: number) => number | null;
138
+ /**
139
+ * Calculate bearing/direction from current position to target coordinates
140
+ * @param latitude - Target latitude in decimal degrees
141
+ * @param longitude - Target longitude in decimal degrees
142
+ * @returns Bearing in degrees (0-360, where 0=North, 90=East, 180=South, 270=West), or null if position unavailable
143
+ */
144
+ bearingTo: (latitude: number, longitude: number) => number | null;
145
+ }
146
+
147
+ /**
148
+ * A React hook for accessing device geolocation with real-time tracking and distance calculation.
149
+ *
150
+ * Features:
151
+ * - Get current position (one-time)
152
+ * - Watch position for real-time updates
153
+ * - Permission state tracking
154
+ * - Distance calculation using Haversine formula
155
+ * - Bearing/direction calculation
156
+ * - SSR compatible
157
+ * - TypeScript support
158
+ *
159
+ * @param options - Configuration options
160
+ * @returns Geolocation state and control functions
161
+ *
162
+ * @example
163
+ * ```tsx
164
+ * // Basic usage - get current position
165
+ * function MyLocation() {
166
+ * const { position, loading, error } = useGeolocation();
167
+ *
168
+ * if (loading) return <p>Loading location...</p>;
169
+ * if (error) return <p>Error: {error.message}</p>;
170
+ * if (!position) return <p>No position yet</p>;
171
+ *
172
+ * return (
173
+ * <div>
174
+ * <p>Latitude: {position.coords.latitude}</p>
175
+ * <p>Longitude: {position.coords.longitude}</p>
176
+ * <p>Accuracy: {position.coords.accuracy}m</p>
177
+ * </div>
178
+ * );
179
+ * }
180
+ * ```
181
+ *
182
+ * @example
183
+ * ```tsx
184
+ * // Real-time tracking with watch
185
+ * function LiveTracking() {
186
+ * const { position, watchPosition, clearWatch } = useGeolocation({
187
+ * immediate: false,
188
+ * watch: false,
189
+ * });
190
+ *
191
+ * return (
192
+ * <div>
193
+ * <button onClick={watchPosition}>Start Tracking</button>
194
+ * <button onClick={clearWatch}>Stop Tracking</button>
195
+ * {position && (
196
+ * <p>Current: {position.coords.latitude}, {position.coords.longitude}</p>
197
+ * )}
198
+ * </div>
199
+ * );
200
+ * }
201
+ * ```
202
+ *
203
+ * @example
204
+ * ```tsx
205
+ * // Distance calculation
206
+ * function DistanceToDestination() {
207
+ * const { position, distanceFrom } = useGeolocation();
208
+ *
209
+ * // New York City coordinates
210
+ * const nyLat = 40.7128;
211
+ * const nyLon = -74.0060;
212
+ *
213
+ * const distance = distanceFrom(nyLat, nyLon);
214
+ *
215
+ * return (
216
+ * <div>
217
+ * {distance && (
218
+ * <p>Distance to NYC: {(distance / 1000).toFixed(2)} km</p>
219
+ * )}
220
+ * </div>
221
+ * );
222
+ * }
223
+ * ```
224
+ *
225
+ * @example
226
+ * ```tsx
227
+ * // With callbacks and high accuracy
228
+ * const geolocation = useGeolocation({
229
+ * enableHighAccuracy: true,
230
+ * timeout: 10000,
231
+ * onSuccess: (pos) => console.log('Got position:', pos),
232
+ * onError: (err) => console.error('Geolocation error:', err),
233
+ * onPositionChange: (pos) => console.log('Position updated:', pos),
234
+ * onPermissionChange: (state) => console.log('Permission:', state),
235
+ * });
236
+ * ```
237
+ */
238
+ declare function useGeolocation(options?: UseGeolocationOptions): UseGeolocationReturn;
239
+
240
+ /**
241
+ * Calculate distance between two points using Haversine formula
242
+ *
243
+ * The Haversine formula determines the great-circle distance between two points
244
+ * on a sphere given their longitudes and latitudes. This assumes a spherical Earth,
245
+ * which introduces an error of up to 0.5% compared to more accurate ellipsoidal models.
246
+ *
247
+ * @param lat1 - Latitude of first point in decimal degrees
248
+ * @param lon1 - Longitude of first point in decimal degrees
249
+ * @param lat2 - Latitude of second point in decimal degrees
250
+ * @param lon2 - Longitude of second point in decimal degrees
251
+ * @returns Distance in meters
252
+ *
253
+ * @example
254
+ * ```typescript
255
+ * // Distance from San Francisco to Los Angeles
256
+ * const distance = haversineDistance(37.7749, -122.4194, 34.0522, -118.2437);
257
+ * console.log(distance); // ~559,000 meters (559 km)
258
+ * ```
259
+ */
260
+ declare function haversineDistance(lat1: number, lon1: number, lat2: number, lon2: number): number;
261
+ /**
262
+ * Calculate initial bearing (forward azimuth) from point 1 to point 2
263
+ *
264
+ * The bearing is the direction you would need to travel from the first point
265
+ * to reach the second point along a great circle path. Note that the bearing
266
+ * may change along the path (except when traveling due north/south or along the equator).
267
+ *
268
+ * @param lat1 - Latitude of first point in decimal degrees
269
+ * @param lon1 - Longitude of first point in decimal degrees
270
+ * @param lat2 - Latitude of second point in decimal degrees
271
+ * @param lon2 - Longitude of second point in decimal degrees
272
+ * @returns Bearing in degrees (0-360, where 0=North, 90=East, 180=South, 270=West)
273
+ *
274
+ * @example
275
+ * ```typescript
276
+ * // Bearing from New York to London
277
+ * const bearing = calculateBearing(40.7128, -74.0060, 51.5074, -0.1278);
278
+ * console.log(bearing); // ~51 degrees (Northeast)
279
+ * ```
280
+ */
281
+ declare function calculateBearing(lat1: number, lon1: number, lat2: number, lon2: number): number;
282
+
283
+ export { type GeoCoordinates, type GeoPosition, type GeolocationError, type GeolocationErrorCode, type PermissionState, type UseGeolocationOptions, type UseGeolocationReturn, calculateBearing, haversineDistance, useGeolocation };