需求
Java计算WGS84坐标系两个点之间的距离,距离可能会较大,
算法
球形模型1
直接采用球形的模型。
/**
* Calculate distance between two points in latitude and longitude taking
* into account height difference. If you are not interested in height
* difference pass 0.0. Uses Haversine method as its base.
* <p>
* lat1, lon1 Start point lat2, lon2 End point el1 Start altitude in meters
* el2 End altitude in meters
*
* @returns Distance in Meters
*/
@Deprecated
public static double distance(double lat1, double lat2, double lon1,
double lon2, double el1, double el2) {
final int R = 6371; // Radius of the earth
double latDistance = Math.toRadians(lat2 - lat1);
double lonDistance = Math.toRadians(lon2 - lon1);
double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2)
+ Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2))
* Math.sin(lonDistance / 2) * Math.sin(lonDistance / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double distance = R * c * 1000; // convert to meters
double height = el1 - el2;
distance = Math.pow(distance, 2) + Math.pow(height, 2);
return Math.sqrt(distance);
}
球形模型2
/**
* 计算距离(千米)
*
* @param fromPoint 起始点
* @param toPoint 终点
* @return 距离
*/
public static double calculateDistance(Point2D.Double fromPoint, Point2D.Double toPoint) {
return distanceWithLljk(fromPoint.getX(), fromPoint.getY(), toPoint.getX(), toPoint.getY()) / 1000.0;
}
private static double distanceWithLljk(double fromLon, double fromLat, double toLon, double toLat) {
//地球半径以及塔台和无人机的经纬高赋值
double r0 = 6371393.0;
double t1 = fromLon;
double t2 = fromLat;
double t3 = 0;
double a1 = toLon;
double a2 = toLat;
double a3 = 0;
//角度转弧度以及距地心距离计算
t1 = t1 / 180.0 * Math.PI;
t2 = t2 / 180.0 * Math.PI;
t3 = t3 + r0;
a1 = a1 / 180.0 * Math.PI;
a2 = a2 / 180.0 * Math.PI;
a3 = a3 + r0;
//地球坐标系
double t11 = t3 * Math.cos(t2) * Math.cos(t1);
double t12 = t3 * Math.cos(t2) * Math.sin(t1);
double t13 = t3 * Math.sin(t2);
double a11 = a3 * Math.cos(a2) * Math.cos(a1);
double a12 = a3 * Math.cos(a2) * Math.sin(a1);
double a13 = a3 * Math.sin(a2);
double x1 = a11 - t11;
double x2 = a12 - t12;
double x3 = a13 - t13;
double r1 = (-Math.sin(t1)) * x1 + Math.cos(t1) * x2;
double r2 = (-Math.sin(t2)) * Math.cos(t1) * x1 + (-Math.sin(t2) * Math.sin(t1)) * x2 + Math.cos(t2) * x3;
double r3 = <