Advertisement
Guest User

Haversine

a guest
Oct 26th, 2016
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.16 KB | None | 0 0
  1. //Calculates distance between two sets of Decimal Degree coordinates using the Haversine formula
  2. //Accepts two sets of longitudes and latitudes in decimal degree format and calculates distance between
  3. //in meters.
  4. signed long get_distance(signed long lat1, signed long lat2, signed long lng1, signed long lng2){
  5.     signed long radius = 6371000;   //Approximate radius of the Earth in meters
  6.     double latDif, lngDif, radLat1, radLat2, a, c, d;
  7.  
  8. //It should be able to handle negatives, but in case it can't...   
  9. //  if(lat1 < 0)
  10. //      lat1 *= -1;
  11. //  
  12. //  if(lat2 < 0)
  13. //      lat2 *= -1;
  14. //  
  15. //  if(lng1 < 0)
  16. //      lng1 *= -1;
  17. //  
  18. //  if(lng2 < 0)
  19. //      lng2 *= -1;
  20.  
  21. //Dividing breaks everything
  22. //  lat1 /= 10000000;
  23. //  lat2 /= 10000000;
  24. //  lng1 /= 10000000;
  25. //  lng2 /= 10000000;
  26.    
  27.     //Convert from degrees to radians
  28.     radLat1 = lat1 * M_PI / 180;
  29.     radLat2 = lat2 * M_PI / 180;
  30.     latDif = (lat2 - lat1) * M_PI / 180;
  31.     lngDif = (lng2 - lng1) * M_PI / 180;
  32.  
  33.     //Apply the Haversine formula
  34.     a = sin(latDif/2) * sin(latDif/2) + cos(radLat1) * cos(radLat2) * sin(lngDif/2) * sin(lngDif/2);
  35.     c = 2 * atan2(sqrt(a), sqrt(1-a));
  36.     d = radius * c;
  37.  
  38.     return (long)d;
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement