1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| public class DistanceCalcUtil {
// 地球半径 private static final double EARTH_RADIUS = 6370996.81;
// 弧度 private static double radian(double d) { return d * Math.PI / 180.0; }
/** * 计算两点之间的距离 * * @param lat1 * @param lng1 * @param lat2 * @param lng2 * @return */ public static double distanceOfTwoPoints(double lat1, double lng1, double lat2, double lng2) { double radLat1 = radian(lat1); double radLat2 = radian(lat2); double a = radLat1 - radLat2; double b = radian(lng1) - radian(lng2); double s = 2 * Math.asin(Math .sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2))); s = s * EARTH_RADIUS; return s; // s = Math.round(s * 10000) / 10000; // Integer distance = Integer.parseInt(new // java.text.DecimalFormat("0").format(s)); // return distance; }
public static void main(String[] args) { System.out.println("经度改变1位,测试:");
System.out.println("小数点后6位,精度:0.1米"); System.out.println(distanceOfTwoPoints(24.234532, 124.123223, 24.234532, 124.123224));
System.out.println("小数点后5位,精度:1米"); System.out.println(distanceOfTwoPoints(24.234532, 124.12322, 24.234532, 124.12323));
System.out.println("小数点后4位,精度:10米"); System.out.println(distanceOfTwoPoints(24.234532, 124.1232, 24.234532, 124.1233));
System.out.println("小数点后3位,精度:101米"); System.out.println(distanceOfTwoPoints(24.234532, 124.123, 24.234532, 124.124));
System.out.println("小数点后3位(经纬度同时改变1位),精度:150米"); System.out.println(distanceOfTwoPoints(24.234, 124.123, 24.235, 124.124));
System.out.println("小数点后2位,精度:1014米"); System.out.println(distanceOfTwoPoints(24.234532, 124.12, 24.234532, 124.13)); } }
|