Advertisement
rplantiko

Distance of two points on a sphere

Mar 25th, 2023 (edited)
681
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Distance of two points on the terrestrial sphere (distance in km, azimut in °)
  2.  
  3. var result = distance({
  4.     lon1: 7.34684,
  5.     lat1: 47.36376,
  6.     lon2: 7.60884,
  7.     lat2: 47.52812
  8. });
  9. console.log(result);
  10.  
  11. function distance({ lon1, lon2, lat1, lat2}) {
  12.  
  13.   let azimut, dist;
  14.   const RADIANS = 0.017453292519943295769236907684886;  // = π / 180°
  15.   const NAUTICAL_MILE = 1.852216;                       // = 1′ of arc in km
  16.  
  17.   lon1 = lon1 * RADIANS;
  18.   lon2 = lon2 * RADIANS;
  19.   lat1 = lat1 * RADIANS;
  20.   lat2 = lat2 * RADIANS;
  21.  
  22.   // Compute the distance arc of distance using the cosine law for spherical triangles
  23.   let a = Math.acos(
  24.             Math.sin( lat1 ) * Math.sin( lat2 ) +
  25.             Math.cos( lat1 ) * Math.cos( lat2 ) * Math.cos( lon1 - lon2 ) );
  26.      
  27.   // Shortest distance in km
  28.   dist = a * 60 * NAUTICAL_MILE / RADIANS;
  29.  
  30.   // Azimut
  31.   azimut = a < 1e-4 ? 0 :
  32.      Math.atan2(
  33.        Math.cos( lat1 ) * Math.sin( lon2-lon1 ),
  34.        Math.sin( lat2 ) * Math.cos( lat1 ) - Math.cos( lon2-lon1 ) * Math.cos( lat2 ) * Math.sin( lat1 )
  35.      ) / RADIANS;
  36.      
  37.   if (azimut < 0) azimut += 360;
  38.  
  39.   return {azimut,dist};
  40.  
  41. }
  42.  
  43.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement