Posted By

rnickel on 10/14/10


Tagged

j2me GPS blackberry


Versions (?)

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


 / Published in: Java
 

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

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.

  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. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: rnickel on October 14, 2010

You can disregard lines 12 and 13. They were put there for debug purposes and I forgot to remove them :D

You need to login to post a comment.