How to calculate the distance between two lat/lon points on the blackberry


/ Published in: Java
Save to your folder(s)

Yes, I realize that this won't work with j2me, but RIM has implemented some good helper classes to make this calculation much easier.

This calculation uses the Haversine formula.


Copy this code and paste it in your HTML
  1. public double calculateDistance(double lat1, double lon1, double lat2, double lon2)
  2. {
  3. try{
  4. double R = 6371; // km
  5.  
  6. double dlat = Math.toRadians(lat2 - lat1);
  7. double dlong = Math.toRadians(lon2 - lon1);
  8.  
  9. double a = Math.sin(dlat / 2.0) * Math.sin(dlat / 2.0) +
  10. Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
  11. Math.sin(dlong / 2.0) * Math.sin(dlong / 2.0);
  12. double num2 = Math.sqrt(a);
  13. double num1 = Math.sqrt(1-a);
  14. double c = 2 * MathUtilities.atan2(Math.sqrt(a), Math.sqrt(1-a));
  15. double d = R * c;
  16.  
  17. return d;
  18.  
  19. } catch(Exception e){
  20. e.printStackTrace();
  21. }
  22. return 0;
  23. }

URL: http://www.ryannickel.com/2010/10/how-to-calculate-the-distance-between-two-latlon-points-on-the-blackberry/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.