使用Java用Vincenty算法根据经纬度计算距离
时间: 2023-11-08 16:04:17 浏览: 276
距离计算,距离计算器,Java
Vincenty算法是一种用于计算地球上两点之间的距离的算法,它考虑了地球的椭球形状和旋转。以下是使用Java实现Vincenty算法计算两点之间距离的代码示例:
```java
public class VincentyDistanceCalculator {
private static final double EQUATORIAL_RADIUS = 6378137.0; // 地球赤道半径,单位:米
private static final double POLAR_RADIUS = 6356752.3; // 地球极半径,单位:米
public static double calculateDistance(double lat1, double lon1, double lat2, double lon2) {
double a = EQUATORIAL_RADIUS;
double b = POLAR_RADIUS;
double f = (a - b) / a;
double L = Math.toRadians(lon2 - lon1);
double U1 = Math.atan((1 - f) * Math.tan(Math.toRadians(lat1)));
double U2 = Math.atan((1 - f) * Math.tan(Math.toRadians(lat2)));
double sinU1 = Math.sin(U1);
double cosU1 = Math.cos(U1);
double sinU2 = Math.sin(U2);
double cosU2 = Math.cos(U2);
double lambda = L;
double lambdaP = 2 * Math.PI;
int iterLimit = 100;
while (Math.abs(lambda - lambdaP) > 1e-12 && iterLimit-- > 0) {
double sinLambda = Math.sin(lambda);
double cosLambda = Math.cos(lambda);
double sinSigma = Math.sqrt((cosU2 * sinLambda) * (cosU2 * sinLambda)
+ (cosU1 * sinU2 - sinU1 * cosU2 * cosLambda) * (cosU1 * sinU2 - sinU1 * cosU2 * cosLambda));
if (sinSigma == 0) {
return 0.0; // 两点重合
}
double cosSigma = sinU1 * sinU2 + cosU1 * cosU2 * cosLambda;
double sigma = Math.atan2(sinSigma, cosSigma);
double sinAlpha = cosU1 * cosU2 * sinLambda / sinSigma;
double cosSqAlpha = 1 - sinAlpha * sinAlpha;
double cos2SigmaM = cosSigma - 2 * sinU1 * sinU2 / cosSqAlpha;
double C = f / 16 * cosSqAlpha * (4 + f * (4 - 3 * cosSqAlpha));
lambdaP = lambda;
lambda = L + (1 - C) * f * sinAlpha
* (sigma + C * sinSigma * (cos2SigmaM + C * cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM)));
}
if (iterLimit == 0) {
throw new RuntimeException("过程未收敛");
}
double uSq = cosSqAlpha * (a * a - b * b) / (b * b);
double A = 1 + uSq / 16384 * (4096 + uSq * (-768 + uSq * (320 - 175 * uSq)));
double B = uSq / 1024 * (256 + uSq * (-128 + uSq * (74 - 47 * uSq)));
double deltaSigma = B * sinSigma
* (cos2SigmaM + B / 4 * (cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM) - B / 6 * cos2SigmaM
* (-3 + 4 * sinSigma * sinSigma) * (-3 + 4 * cos2SigmaM * cos2SigmaM)));
double s = b * A * (sigma - deltaSigma);
return s;
}
}
```
该算法中的参数lat1、lon1、lat2和lon2分别表示两点的纬度和经度,单位为度。函数返回值表示两点之间的距离,单位为米。需要注意的是,该算法中的距离是基于地球表面的,不考虑地球内部的变化。
阅读全文