在Android google map中,有时候会碰到计算两地的距离,下面的辅助类就可以帮助你计算距离:
1 public class DistanceHelper { 2 /** Names for the units to use */ 3 public final static int KILOMETERS = 0; 4 public final static int STATUTE_MILES = 1; 5 public final static int NAUTICAL_MILES = 2; 6 7 /** Radius of the Earth in the units above */ 8 private final static double EARTHS_RADIUS[] = { 6378.1, // Kilometers 9 3963.1676, // Statue miles 10 3443.89849 // Nautical miles 11 }; 12 13 /** Conversion factor to convert from degrees to radians */ 14 private static final double DEGREES_TO_RADIANS = (180 / Math.PI); 15 16 /** 17 * Calculates the "length" of an arc between two points on a sphere given 18 * the latitude & longitude of those points. 19 * 20 * @param aLat 21 * Latitude of point A 22 * @param aLong 23 * Longitude of point A 24 * @param bLat 25 * Latitude of point B 26 * @param bLong 27 * Longitude of point B 28 * @return 29 */ 30 private static double calclateArc(double aLat, double aLong, double bLat, 31 double bLong) { 32 /* 33 * Convert location a and b's lattitude and longitude from degrees to 34 * radians 35 */ 36 double aLatRad = aLat / DEGREES_TO_RADIANS; 37 double aLongRad = aLong / DEGREES_TO_RADIANS; 38 double bLatRad = bLat / DEGREES_TO_RADIANS; 39 double bLongRad = bLong / DEGREES_TO_RADIANS; 40 41 // Calculate the length of the arc that subtends point a and b 42 double t1 = Math.cos(aLatRad) * Math.cos(aLongRad) * Math.cos(bLatRad) 43 * Math.cos(bLongRad); 44 double t2 = Math.cos(aLatRad) * Math.sin(aLongRad) * Math.cos(bLatRad) 45 * Math.sin(bLongRad); 46 double t3 = Math.sin(aLatRad) * Math.sin(bLatRad); 47 double tt = Math.acos(t1 + t2 + t3); 48 49 // Return a "naked" length for the calculated arc 50 return tt; 51 } 52 53 /** 54 * Calculates the distance between two addresses 55 * 56 * @param pointA 57 * GeoPoint of point A 58 * @param pointB 59 * GeoPoint of point B 60 * @param units 61 * Desired units 62 * @return Distance between the two points in the desired units 63 */ 64 public static double calculateDistance(GeoPoint pointA, GeoPoint pointB, 65 int units) { 66 return calclateArc(pointA.getLatitudeE6() / 1E6, 67 pointA.getLongitudeE6() / 1E6, pointB.getLatitudeE6() / 1E6, 68 pointB.getLongitudeE6() / 1E6) * EARTHS_RADIUS[units]; 69 } 70 71 /** 72 * Calculates the distance between two locations 73 * 74 * @param pointA 75 * Location of point A 76 * @param pointB 77 * Location of point B 78 * @param units 79 * Desired units 80 * @return Distance between the two points in the desired units 81 */ 82 public static double calculateDistance(Location pointA, Location pointB, 83 int units) { 84 return calclateArc(pointA.getLatitude(), pointA.getLongitude(), 85 pointB.getLatitude(), pointB.getLongitude()) 86 * EARTHS_RADIUS[units]; 87 } 88 }