Bắt đầu sửa lỗi
This commit is contained in:
@@ -0,0 +1,61 @@
|
||||
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 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}`;
|
||||
}
|
||||
Reference in New Issue
Block a user