1.球面计算
public static void main(String[] args) {
double x = 104.07966;
double y = 30.581751;
double x1 = 104.072833;
double y1 = 30.58172;
System.out.println(getDistance(x,y,x1,y1));
}
/**
* 角度弧度计算公式 rad
* 360度=2π π=Math.PI
* x度 = x*π/360 弧度
* @param degree
* @since JDK 1.8
*/
private static double getRadian(double degree) {
return degree * Math.PI / 180.0;
}
/**
* 根据经纬度计算两点之间的距离 GetDistance
* @param lat1 1纬度
* @param lng1 1经度
* @param lat2 2纬度
* @param lng2 2经度
* @return 距离 单位 米
* @since JDK 1.8
*/
public static double getDistance(double lat1, double lng1, double lat2, double lng2){
double radLat1 = getRadian(lat1);
double radLat2 = getRadian(lat2);
double a = radLat1 - radLat2;// 两点纬度差
double b = getRadian(lng1) - getRadian(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 * 6371000;
return s * ;
}
计算所得结果为:759.128米
2.GlobalCoordinates计算方式:
引入maven依赖包
<dependency>
<groupId>org.gavaghan</groupId>
<artifactId>geodesy</artifactId>
<version>1.1.3</version>
</dependency>
public class CaculateDistanceTest{
public static void main(String[] args){
GlobalCoordinates source = new GlobalCoordinates(30.581751, 104.07966);
GlobalCoordinates target = new GlobalCoordinates(30.58172, 104.072833);
double meter1 = getDistanceMeter(source, target, Ellipsoid.Sphere);
double meter2 = getDistanceMeter(source, target, Ellipsoid.WGS84);
System.out.println("Sphere计算结果:"+meter1 + "米");
System.out.println("WGS84计算结果:"+meter2 + "米");
}
public static double getDistanceMeter(GlobalCoordinates gpsFrom, GlobalCoordinates gpsTo, Ellipsoid ellipsoid){
//创建GeodeticCalculator,调用计算方法,传入坐标系、经纬度用于计算距离
GeodeticCurve geoCurve = new GeodeticCalculator().calculateGeodeticCurve(ellipsoid, gpsFrom, gpsTo);
return geoCurve.getEllipsoidalDistance();
}
}
计算结果为:
Sphere坐标系计算结果:653.545
WGS84坐标系计算结果:654.845