@sv-use/core
Version:
A collection of Svelte 5 utilities.
67 lines (66 loc) • 1.97 kB
JavaScript
import { onDestroy } from 'svelte';
/**
* It allows the user to provide their location to web applications if they so desire.
*
* For privacy reasons, the user is asked for permission to report location information.
* @param options Additional options to customize the behavior.
* @see https://svelte-librarian.github.io/sv-use/docs/core/get-geolocation
*/
export function getGeolocation(options = {}) {
const { enableHighAccuracy = true, maximumAge = 30000, timeout = 27000, autoCleanup = true, immediate = true } = options;
const _isSupported = $derived.by(() => navigator && 'geolocation' in navigator);
let _watcherId = $state();
let _coords = $state({
accuracy: 0,
latitude: Number.POSITIVE_INFINITY,
longitude: Number.POSITIVE_INFINITY,
altitude: null,
altitudeAccuracy: null,
heading: null,
speed: null
});
let _timestamp = $state(0);
let _error = $state(null);
if (immediate) {
resume();
}
if (autoCleanup) {
onDestroy(() => pause());
}
function resume() {
if (!_isSupported)
return;
_watcherId = navigator.geolocation.watchPosition((position) => {
_coords = position.coords;
_timestamp = Date.now();
}, (error) => {
_error = error;
}, {
enableHighAccuracy: enableHighAccuracy,
maximumAge: maximumAge,
timeout: timeout
});
}
function pause() {
if (!_isSupported || !_watcherId)
return;
navigator.geolocation.clearWatch(_watcherId);
}
return {
get isSupported() {
return _isSupported;
},
get coords() {
return _coords;
},
get timestamp() {
return _timestamp;
},
get error() {
return _error;
},
resume,
pause,
cleanup: pause
};
}