distanceCalculator.tsx 1.3 KB

123456789101112131415161718192021222324252627282930313233343536
  1. import * as Location from 'expo-location';
  2. export const calculateDistance = async (
  3. stationLat: number,
  4. stationLng: number,
  5. currentLocation?: Location.LocationObject
  6. ): Promise<number | null> => {
  7. try {
  8. if (!currentLocation) {
  9. let { status } = await Location.requestForegroundPermissionsAsync();
  10. if (status !== 'granted') {
  11. throw new Error('Permission to access location was denied');
  12. }
  13. currentLocation = await Location.getLastKnownPositionAsync({});
  14. }
  15. const { latitude: lat1, longitude: lon1 } = currentLocation.coords;
  16. const lat2 = stationLat;
  17. const lon2 = stationLng;
  18. const R = 6371e3; // Earth's radius in meters
  19. const φ1 = (lat1 * Math.PI) / 180;
  20. const φ2 = (lat2 * Math.PI) / 180;
  21. const Δφ = ((lat2 - lat1) * Math.PI) / 180;
  22. const Δλ = ((lon2 - lon1) * Math.PI) / 180;
  23. const a =
  24. Math.sin(Δφ / 2) * Math.sin(Δφ / 2) + Math.cos(φ1) * Math.cos(φ2) * Math.sin(Δλ / 2) * Math.sin(Δλ / 2);
  25. const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  26. return R * c; // Distance in meters
  27. } catch (error) {
  28. console.error('Error calculating distance:', error);
  29. return null;
  30. }
  31. };