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

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();
    }

}
相关推荐
荔枝吻9 分钟前
【沉浸式解决问题】idea开发中mapper类中突然找不到对应实体类
java·intellij-idea·mybatis
2301_8050545624 分钟前
Python训练营打卡Day59(2025.7.3)
开发语言·python
snoopyfly~24 分钟前
Ubuntu 24.04 LTS 服务器配置:安装 JDK、Nginx、Redis。
java·服务器·ubuntu
lsx2024061 小时前
CSS 网页布局:从基础到进阶
开发语言
挺菜的1 小时前
【算法刷题记录(简单题)003】统计大写字母个数(java代码实现)
java·数据结构·算法
蜗牛沐雨1 小时前
警惕 Rust 字符串的性能陷阱:`chars().nth()` 的深坑与高效之道
开发语言·后端·rust
2401_858286111 小时前
125.【C语言】数据结构之归并排序递归解法
c语言·开发语言·数据结构·算法·排序算法·归并排序
掘金-我是哪吒2 小时前
分布式微服务系统架构第156集:JavaPlus技术文档平台日更-Java线程池使用指南
java·分布式·微服务·云原生·架构
亲爱的非洲野猪2 小时前
Kafka消息积压的多维度解决方案:超越简单扩容的完整策略
java·分布式·中间件·kafka
wfsm2 小时前
spring事件使用
java·后端·spring