geo.ts 837 B

12345678910111213141516171819202122232425262728293031
  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. * @param lat1
  12. * @param lon1
  13. * @param lat2
  14. * @param lon2
  15. * @returns {number}
  16. */
  17. function sphericDistance (lat1: number, lon1: number, lat2: number, lon2: number): number {
  18. const R = 6371 // km
  19. const dLat = toRad(lat2 - lat1)
  20. const dLon = toRad(lon2 - lon1)
  21. lat1 = toRad(lat1)
  22. lat2 = toRad(lat2)
  23. const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
  24. Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2)
  25. const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
  26. return R * c
  27. }
  28. export default sphericDistance