准备工作
<dependency>
<groupId>org.gavaghan</groupId>
<artifactId>geodesy</artifactId>
<version>1.1.3</version>
</dependency>
示例调用
public static Float getDistance(Float lon1, Float lat1, Float lon2, Float lat2) {
GlobalCoordinates source = new GlobalCoordinates(lat1, lon1);
GlobalCoordinates target = new GlobalCoordinates(lat2, lon2);
GeodeticCurve geoCurve = new GeodeticCalculator().calculateGeodeticCurve(Ellipsoid.Sphere, source, target);
double distance = geoCurve.getEllipsoidalDistance();
BigDecimal distanceBig = new BigDecimal(distance).setScale(2, RoundingMode.UP);
distanceBig = distanceBig.multiply(new BigDecimal("0.001")).setScale(2, RoundingMode.UP);
return Float.parseFloat(String.valueOf(distanceBig));
}
封装工具类
public class DistanceUtils {
public static String getDistance(String lon1, String lat1, String lon2, String lat2) {
GlobalCoordinates source = new GlobalCoordinates(Double.parseDouble(lat1), Double.parseDouble(lon1));
GlobalCoordinates target = new GlobalCoordinates(Double.parseDouble(lat2), Double.parseDouble(lon2));
GeodeticCurve geoCurve = new GeodeticCalculator().calculateGeodeticCurve(Ellipsoid.Sphere, source, target);
double distance = geoCurve.getEllipsoidalDistance();
BigDecimal distanceBig = new BigDecimal(distance).setScale(2, RoundingMode.UP);
distanceBig = distanceBig.multiply(new BigDecimal("0.001")).setScale(2, RoundingMode.UP);
return distanceBig.toString().concat("km");
}
public static Double getDistance(Double lon1, Double lat1, Double lon2, Double lat2) {
GlobalCoordinates source = new GlobalCoordinates(lat1, lon1);
GlobalCoordinates target = new GlobalCoordinates(lat2, lon2);
GeodeticCurve geoCurve = new GeodeticCalculator().calculateGeodeticCurve(Ellipsoid.Sphere, source, target);
double distance = geoCurve.getEllipsoidalDistance();
BigDecimal distanceBig = new BigDecimal(distance).setScale(2, RoundingMode.UP);
distanceBig = distanceBig.multiply(new BigDecimal("0.001")).setScale(2, RoundingMode.UP);
return Double.parseDouble(String.valueOf(distanceBig));
}
public static Float getDistance(Float lon1, Float lat1, Float lon2, Float lat2) {
GlobalCoordinates source = new GlobalCoordinates(lat1, lon1);
GlobalCoordinates target = new GlobalCoordinates(lat2, lon2);
GeodeticCurve geoCurve = new GeodeticCalculator().calculateGeodeticCurve(Ellipsoid.Sphere, source, target);
double distance = geoCurve.getEllipsoidalDistance();
BigDecimal distanceBig = new BigDecimal(distance).setScale(2, RoundingMode.UP);
distanceBig = distanceBig.multiply(new BigDecimal("0.001")).setScale(2, RoundingMode.UP);
return Float.parseFloat(String.valueOf(distanceBig));
}
}