经纬度计算两地距离

 1 public final class DistanceUtils {
 2 
 3     /**
 4      * 地球半径,单位 km
 5      */
 6     private static final double EARTH_RADIUS = 6378.137;
 7 
 8     /**
 9      * 根据经纬度,计算两点间的距离
10      *
11      * @param longitude1 第一个点的经度
12      * @param latitude1  第一个点的纬度
13      * @param longitude2 第二个点的经度
14      * @param latitude2  第二个点的纬度
15      * @return 返回距离 单位千米
16      */
17     public static double getDistance(double longitude1, double latitude1, double longitude2, double latitude2) {
18         // 纬度
19         double lat1 = Math.toRadians(latitude1);
20         double lat2 = Math.toRadians(latitude2);
21         // 经度
22         double lng1 = Math.toRadians(longitude1);
23         double lng2 = Math.toRadians(longitude2);
24         // 纬度之差
25         double a = lat1 - lat2;
26         // 经度之差
27         double b = lng1 - lng2;
28         // 计算两点距离的公式
29         double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
30                 Math.cos(lat1) * Math.cos(lat2) * Math.pow(Math.sin(b / 2), 2)));
31         // 弧长乘地球半径, 返回单位: 千米
32         s =  s * EARTH_RADIUS;
33         return s;
34     }
35 
36     public static void main(String[] args) {
37         double d = getDistance(116.308479, 39.983171, 116.353454, 39.996059);
38         System.out.println(d);
39     }
40 }

 

posted @ 2019-10-27 20:42  lanwf  阅读(1542)  评论(0编辑  收藏  举报