Advertisement
Guest User

Untitled

a guest
Feb 22nd, 2017
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.11 KB | None | 0 0
  1. public class Convert {
  2.  
  3. public double calc(double currentLat, double currentLng, double goalLat, double goalLng) {
  4. // Earth radius
  5. double R = 6371000;
  6.  
  7. double radCurrentLat = Math.toRadians(currentLat);
  8. double radGoalLat = Math.toRadians(goalLat);
  9. double diffLat = Math.toRadians(goalLat - currentLat);
  10. double diffLng = Math.toRadians(goalLng - currentLng);
  11.  
  12.  
  13. // Haversine formula
  14. double a = Math.sin(diffLat / 2) * Math.sin(diffLat / 2) +
  15. Math.cos(radCurrentLat) * Math.cos(radGoalLat) *
  16. Math.sin(diffLng / 2) * Math.sin(diffLng / 2);
  17.  
  18. double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  19.  
  20. // Distance given in meters
  21. return R * c;
  22. }
  23.  
  24. public static void main(String[] args) {
  25. Convert c = new Convert();
  26.  
  27. double distance = c.calc(4100.0, -74.0, 40.0, -74.006);
  28.  
  29. // If number is to big, c.calc(4100.0, -74.0, 40.0, -74.006)
  30. // will return 1.111949264364013E7 that will be 11.120 km
  31. System.out.println(distance);
  32. }
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement