package com.didichuxing.dd596.lcl.order.common.util;
import org.gavaghan.geodesy.Ellipsoid;
import org.gavaghan.geodesy.GeodeticCalculator;
import org.gavaghan.geodesy.GlobalCoordinates;
import java.math.BigDecimal;
public class DistanceUtils {
private static double EARTH_RADIUS = 6378.137 * 1000;
private static double rad(double d) {
return d * Math.PI / 180.0;
}
//方法1
private static double getDistance(double lat1, double lng1, double lat2, double lng2) {
double radLat1 = rad(lat1);
double radLat2 = rad(lat2);
double difference = radLat1 - radLat2;
double mdifference = rad(lng1) - rad(lng2);
double distance = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(difference / 2), 2)
+ Math.cos(radLat1) * Math.cos(radLat2)
* Math.pow(Math.sin(mdifference / 2), 2)));
distance = distance * EARTH_RADIUS;
/**
distance = Math.round(distance * 10000) / 10000;
String distanceStr = distance+"";
distanceStr = distanceStr.
substring(0, distanceStr.indexOf("."));
return distanceStr;
*/
return distance;
}
/**
* //方法2 需导入包
<dependency>
<groupId>org.gavaghan</groupId>
<artifactId>geodesy</artifactId>
<version>1.1.3</version>
</dependency>
* @param lat1 纬度1
* @param lng1 经度1
* @param lat2 纬度2
* @param lng2 经度2
* @return 两地间的距离 米
*/
private static double getGlobalDistance(double lat1, double lng1, double lat2, double lng2) {
GlobalCoordinates source = new GlobalCoordinates(lat1, lng1);
GlobalCoordinates target = new GlobalCoordinates(lat2, lng2);
return new GeodeticCalculator().calculateGeodeticCurve(Ellipsoid.Sphere, source, target).getEllipsoidalDistance();
}
/**
* 需导入包
*
* @param lat1 纬度1
* @param lng1 经度1
* @param lat2 纬度2
* @param lng2 经度2
* @param accurate 精度
* @return 两点间距离 单位km
*/
public static double getDistance(double lat1, double lng1, double lat2, double lng2,int accurate) {
double distance = getDistance(lat1, lng1, lat2, lng2);
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(40.0708d, 116.336116d, 40.053032d, 116.41235d,4);
System.out.println("经纬度距离计算结果:" + result + "千米");
}
}
public class GeoHashUtil {
private static double ratio = Math.PI / 180;
private static double R = 6378137;
/**
* 计算两点之间的距离(地球的球面距离),单位米
*
* @param startLng 开始经度
* @param startLat 开始纬度
* @param endLng 结束经度
* @param endLat 结束维度
* @return 如果以上参数任意一个为null, 则距离返回null
*/
public static Double getDistance(Double startLng, Double startLat, Double endLng, Double endLat) {
if (startLat == null || startLng == null || endLat == null || endLng == null) {
return null;
}
double slon = startLng * ratio;
double slat = startLat * ratio;
double elon = endLng * ratio;
double elat = endLat * ratio;
double c = Math.sin(slat) * Math.sin(elat) + Math.cos(slat) * Math.cos(elat) * Math.cos(slon - elon);
double acos = R * Math.acos(c);
return acos;
}
}