geo.ts 887 B

123456789101112131415161718192021222324252627282930313233
  1. /**
  2. * Converts numeric degrees to radians
  3. * @param val
  4. * @returns {number}
  5. */
  6. function toRad (val: number): number {
  7. return val * Math.PI / 180
  8. }
  9. /**
  10. * This function takes in latitude and longitude of two location and returns the distance between them as the crow flies (in km)
  11. * Implementation of the Haversine formula
  12. *
  13. * @param lat1
  14. * @param lon1
  15. * @param lat2
  16. * @param lon2
  17. * @returns {number}
  18. */
  19. function sphericalDistance (lat1: number, lon1: number, lat2: number, lon2: number): number {
  20. const R = 6371 // km
  21. const dLat = toRad(lat2 - lat1)
  22. const dLon = toRad(lon2 - lon1)
  23. lat1 = toRad(lat1)
  24. lat2 = toRad(lat2)
  25. const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
  26. Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2)
  27. const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
  28. return R * c
  29. }
  30. export default sphericalDistance