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

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

}
相关推荐
罗超驿32 分钟前
15.JavaScript 函数与作用域完全指南:语法、参数、表达式与作用域链实战
开发语言·前端·javascript
江南十四行32 分钟前
并发编程(七)
java
.千余34 分钟前
【C++】C++类与对象2:C++构造函数、运算符重载与流输入输出全面解析
c语言·开发语言·前端·c++·经验分享
郭涤生40 分钟前
C++ 高性能状态机
开发语言·c++
SOC罗三炮1 小时前
OpenHuman 源码深度解构:一个 Rust 驱动的本地优先 AI 个人助手
开发语言·人工智能·rust
亦暖筑序1 小时前
单模型成本高、风险大?Spring AI多模型路由实战:成本降70%,可用性更稳
java·后端·ai编程
404号扳手1 小时前
Java 进阶知识(二)
java·后端
心怀梦想的咸鱼1 小时前
OpenCode 接入 API 报错 read ECONNRESET:基于环境变量的证书校验绕过方案
开发语言·php
SamDeepThinking1 小时前
一个业务场景只需要一个ThreadLocal实例
java·后端·程序员
程序大视界1 小时前
【Python系列课程】Python入门教程
开发语言·人工智能·python