webdev-power-kit
Version:
A powerful toolkit that simplifies access to browser features like clipboard, notifications, battery, vibration, and more — perfect for modern web developers.
47 lines (46 loc) • 1.5 kB
JavaScript
/**
* Get current geolocation from user's device.
*/
export function getCurrentLocation(options) {
return new Promise((resolve, reject) => {
if (!navigator.geolocation) {
return reject(new Error("Geolocation is not supported by this browser."));
}
navigator.geolocation.getCurrentPosition((pos) => {
const coords = pos.coords;
resolve({
latitude: coords.latitude,
longitude: coords.longitude,
accuracy: coords.accuracy,
altitude: coords.altitude,
heading: coords.heading,
speed: coords.speed,
timestamp: pos.timestamp
});
}, (err) => reject(err), options);
});
}
/**
* Continuously track user location.
* @returns Watch ID to use with clearLocationWatch()
*/
export function watchLocation(callback, errorCallback, options) {
return navigator.geolocation.watchPosition((pos) => {
const coords = pos.coords;
callback({
latitude: coords.latitude,
longitude: coords.longitude,
accuracy: coords.accuracy,
altitude: coords.altitude,
heading: coords.heading,
speed: coords.speed,
timestamp: pos.timestamp
});
}, errorCallback ?? (() => { }), options);
}
/**
* Clear a location watch using its ID.
*/
export function clearLocationWatch(id) {
navigator.geolocation.clearWatch(id);
}