This utility provides a simple, Promise-based way to access the user's geolocation in the browser using the Geolocation API, written in TypeScript.
- β Promise-based API
- π Retrieves
latitude,longitude, andaccuracy - π Graceful fallback if geolocation is not supported
- βοΈ Customizable options like high accuracy, timeout, and max age
import { getGeolocationData } from './utils/geolocation';
getGeolocationData()
.then((location) => {
console.log('Location data:', location);
})
.catch((error) => {
console.error('Geolocation error:', error.message);
});interface GeolocationResponse {
latitude: number;
longitude: number;
accuracy: number;
}
export const getGeolocationData = (): Promise<GeolocationResponse> => {
return new Promise((resolve, reject) => {
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition(
(position) => {
const locationData: GeolocationResponse = {
latitude: position.coords.latitude,
longitude: position.coords.longitude,
accuracy: position.coords.accuracy
};
resolve(locationData);
},
(error) => {
reject(new Error(`Geolocation error: ${error.message}`));
},
{
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
}
);
} else {
reject(new Error("Geolocation is not supported by this browser."));
}
});
}If the browser does not support geolocation, the promise is rejected with a clear error message:
"Geolocation is not supported by this browser."
Modern browsers require users to grant explicit permission to access location. Make sure you handle rejections gracefully in your app.
You can place the utility like this:
src/
βββ utils/
βββ geolocation.ts
MIT β feel free to use, modify, and contribute!
π Accurate user location with a simple Promise β great for maps, weather, or personalized experiences.