通过经纬度计算两点之间的距离

1. 相关依赖

xml 复制代码
	<!--计算距离-->
	<dependency>
		<groupId>org.gavaghan</groupId>
		<artifactId>geodesy</artifactId>
		<version>1.1.3</version>
	</dependency>

2.具体的工具类的实现

java 复制代码
import org.gavaghan.geodesy.Ellipsoid;
import org.gavaghan.geodesy.GeodeticCalculator;
import org.gavaghan.geodesy.GeodeticCurve;
import org.gavaghan.geodesy.GlobalCoordinates;

import java.math.BigDecimal;

public class CalculatedDistanceUtils {


    /**
     * @param sourceLongitude 来源经度(用户)
     * @param sourceLatitude 来源纬度(用户)
     * @param targetLongitude 目标经度
     * @param targetLatitude 目标纬度
     * @return 米
     */
    public static double getDistanceMeter(BigDecimal sourceLongitude, BigDecimal sourceLatitude, BigDecimal targetLongitude, BigDecimal targetLatitude){

        //可能会出现用户经纬度为空的情况,那就返回个-1
        if (sourceLongitude == null || sourceLatitude == null){
            return -1;
        }

        GlobalCoordinates source = new GlobalCoordinates(sourceLatitude.doubleValue(), sourceLongitude.doubleValue());
        GlobalCoordinates target = new GlobalCoordinates(targetLatitude.doubleValue(), targetLongitude.doubleValue());

        return getDistanceMeter(source, target, Ellipsoid.Sphere);
    }


    public static double getDistanceMeter(GlobalCoordinates gpsFrom, GlobalCoordinates gpsTo, Ellipsoid ellipsoid){

        //创建GeodeticCalculator,调用计算方法,传入坐标系、经纬度用于计算距离
        GeodeticCurve geoCurve = new GeodeticCalculator().calculateGeodeticCurve(ellipsoid, gpsFrom, gpsTo);

        return geoCurve.getEllipsoidalDistance();
    }

}
相关推荐
雨中飘荡的记忆13 小时前
保证金系统入门到实战
java·后端
Nyarlathotep011313 小时前
Java内存模型
java
暮色妖娆丶17 小时前
不过是吃了几年互联网红利罢了,我高估了自己
java·后端·面试
NE_STOP18 小时前
MyBatis-参数处理与查询结果映射
java
狂奔小菜鸡18 小时前
Day40 | Java中的ReadWriteLock读写锁
java·后端·java ee
SimonKing19 小时前
JetBrains 用户狂喜!这个 AI 插件让 IDE 原地进化成「智能编码助手」
java·后端·程序员
狂奔小菜鸡19 小时前
Day39 | Java中更灵活的锁ReentrantLock
java·后端·java ee
NE_STOP1 天前
MyBatis-配置文件解读及MyBatis为何不用编写Mapper接口的实现类
java
后端AI实验室2 天前
用AI写代码,我差点把漏洞发上线:血泪总结的10个教训
java·ai