74 lines
2.4 KiB
TypeScript
74 lines
2.4 KiB
TypeScript
import * as Location from 'expo-location';
|
|
import { GPSInfo } from '../types';
|
|
|
|
export async function requestLocationPermissions(): Promise<boolean> {
|
|
try {
|
|
const { status } = await Location.requestForegroundPermissionsAsync();
|
|
return status === 'granted';
|
|
} catch (error) {
|
|
console.error('Error requesting location permissions:', error);
|
|
return false;
|
|
}
|
|
}
|
|
|
|
export async function getCurrentGPS(): Promise<GPSInfo | null> {
|
|
try {
|
|
const hasPermission = await requestLocationPermissions();
|
|
if (!hasPermission) return null;
|
|
|
|
const location = await Location.getCurrentPositionAsync({
|
|
accuracy: Location.Accuracy.Balanced,
|
|
});
|
|
|
|
const { latitude, longitude } = location.coords;
|
|
let locality = 'UNKNOWN LOCATION';
|
|
let country = '';
|
|
|
|
try {
|
|
const geocode = await Location.reverseGeocodeAsync({ latitude, longitude });
|
|
if (geocode && geocode.length > 0) {
|
|
const address = geocode[0];
|
|
// Combine city, region, street or subregion to form a retro looking place string
|
|
locality = address.subregion || address.city || address.district || address.region || 'LOCAL REGION';
|
|
locality = locality.toUpperCase();
|
|
country = (address.country || '').toUpperCase();
|
|
}
|
|
} catch (e) {
|
|
console.warn('Reverse geocoding failed, using coordinates only:', e);
|
|
}
|
|
|
|
return {
|
|
latitude,
|
|
longitude,
|
|
locality,
|
|
country,
|
|
timestamp: location.timestamp,
|
|
};
|
|
} catch (error) {
|
|
console.error('Error fetching GPS info:', error);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
export async function reverseGeocode(latitude: number, longitude: number): Promise<string | null> {
|
|
try {
|
|
const geo = await Location.reverseGeocodeAsync({ latitude, longitude });
|
|
if (geo && geo.length > 0) {
|
|
return (geo[0].subregion || geo[0].city || geo[0].region || '').toUpperCase() || null;
|
|
}
|
|
} catch (e) {
|
|
console.warn('Reverse geocode failed:', e);
|
|
}
|
|
return null;
|
|
}
|
|
|
|
export function formatCoordinate(val: number, type: 'lat' | 'lon'): string {
|
|
const absolute = Math.abs(val);
|
|
const degrees = Math.floor(absolute);
|
|
const minutes = Math.floor((absolute - degrees) * 60);
|
|
const seconds = ((absolute - degrees - minutes / 60) * 3600).toFixed(2);
|
|
const direction = type === 'lat' ? (val >= 0 ? 'N' : 'S') : (val >= 0 ? 'E' : 'W');
|
|
|
|
return `${degrees}° ${minutes}' ${seconds}" ${direction}`;
|
|
}
|