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

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

}
相关推荐
跟着汪老师学编程2 分钟前
44、Spring Boot 详细讲义(一)
java·spring boot·后端
ℳ₯㎕ddzོꦿ࿐3 分钟前
Spring Boot 中集成 Knife4j:解决文件上传不显示文件域的问题
java·spring boot·spring
MarvinP10 分钟前
python基础:位置互换
开发语言·python·算法
Gauss松鼠会12 分钟前
GaussDB回调机制深度实践:从事件驱动到系统集成
开发语言·javascript·数据库·sql·gaussdb
独隅12 分钟前
Lua 函数使用的完整指南
开发语言·junit·lua·lua5.4
s_yellowfish18 分钟前
Maven笔记
java·笔记·maven
清霜之辰36 分钟前
详解 kotlin 相对 Java 特有的关键字及使用
android·java·kotlin
江沉晚呤时38 分钟前
深入解析策略模式在C#中的应用与实现
java·服务器·开发语言·前端·.netcore
居然是阿宋39 分钟前
Kotlin 中的 `reified` 关键字全解析:保留类型信息 + 优化高阶函数的双重魔法
android·开发语言·kotlin
Hamm40 分钟前
如何在TypeScript里使用类封装枚举来实现Java的枚举形参倒置
java·前端·typescript