54 lines
1.7 KiB
TypeScript
54 lines
1.7 KiB
TypeScript
export type GeolocationResult = {
|
|
latitude: number;
|
|
longitude: number;
|
|
};
|
|
|
|
export function useGeolocation() {
|
|
function getCurrentPosition(): Promise<GeolocationResult> {
|
|
return new Promise((resolve, reject) => {
|
|
if (!navigator.geolocation) {
|
|
reject(new Error('Perangkat tidak mendukung geolokasi.'));
|
|
|
|
return;
|
|
}
|
|
|
|
navigator.geolocation.getCurrentPosition(
|
|
(position) => {
|
|
resolve({
|
|
latitude: position.coords.latitude,
|
|
longitude: position.coords.longitude,
|
|
});
|
|
},
|
|
(error) => {
|
|
const messages: Record<number, string> = {
|
|
1: 'Izin lokasi ditolak. Aktifkan izin lokasi untuk presensi.',
|
|
2: 'Lokasi tidak tersedia. Coba lagi.',
|
|
3: 'Waktu permintaan lokasi habis. Coba lagi.',
|
|
};
|
|
|
|
reject(new Error(messages[error.code] ?? 'Gagal mendapatkan lokasi.'));
|
|
},
|
|
{
|
|
enableHighAccuracy: true,
|
|
timeout: 15000,
|
|
maximumAge: 0,
|
|
},
|
|
);
|
|
});
|
|
}
|
|
|
|
function buildLocationTag(latitude: number, longitude: number): string {
|
|
const timestamp = new Intl.DateTimeFormat('id-ID', {
|
|
dateStyle: 'medium',
|
|
timeStyle: 'medium',
|
|
}).format(new Date());
|
|
|
|
return `${latitude.toFixed(6)}, ${longitude.toFixed(6)}\n${timestamp}`;
|
|
}
|
|
|
|
return {
|
|
getCurrentPosition,
|
|
buildLocationTag,
|
|
};
|
|
}
|