最近碰到一个需求,需要根据两个点的经纬度查询两点的距离。感觉以后还会用到,所以小记一波。
第一步:添加Maven依赖。
org.gavaghan
geodesy
1.1.3
1
2
3
4
5
第二步:代码实现。
package io.renren.common.utils;
import org.gavaghan.geodesy.Ellipsoid;
import org.gavaghan.geodesy.GeodeticCalculator;
import org.gavaghan.geodesy.GlobalCoordinates;
import java.math.BigDecimal;
public class DistanceUtils {
public static double
getDistance(double longitudeFrom, double latitudeFrom, double
longitudeTo, double latitudeTo) {
GlobalCoordinates source = new
GlobalCoordinates(latitudeFrom, longitudeFrom);
GlobalCoordinates target = new
GlobalCoordinates(latitudeTo, longitudeTo);
return new
GeodeticCalculator().calculateGeodeticCurve(Ellipsoid.Sphere,
source, target).getEllipsoidalDistance();
}
public static double
getDistance(double longitudeFrom, double latitudeFrom, double
longitudeTo, double latitudeTo,int accurate) {
double distance = getDistance(longitudeFrom,
latitudeFrom, longitudeTo, latitudeTo);
if (accurate < 0) {
throw new
RuntimeException("精确度必须是正整数或零");
}
return new BigDecimal(distance).divide(new
BigDecimal(1000),accurate,
BigDecimal.ROUND_HALF_UP).doubleValue();
}
public static void
main(String[] args) {
double result = getDistance(116.336116, 40.0708,
116.41235, 40.053032,0);
System.out.println("经纬度距离计算结果:" + result+
"千米");
}
}
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
————————————————
版权声明:本文为CSDN博主「lihongbo1215」的原创文章,遵循CC 4.0
BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/lihongbo1215/article/details/119459155
加载中,请稍候......