gpt4 book ai didi

java - 计算两个 long/lat 之间的距离

转载 作者:行者123 更新时间:2023-11-29 05:06:52 25 4
gpt4 key购买 nike

经过大量研究但没有找到解决方案后,我不得不问。如何计算 Mysql 中两个 Long/Lat 点之间的距离? (高效的方式?)

我还找到了this解决方案,但我不知道 @lat @long 是哪个,我没有使用 Points 因为 spring-data-jpa 不允许几何类型(除了使用 MysqlSpatial 方言)

在 Java 中我是这样计算的:

private double getDistanceFromLatLonInKm(double lat1,double lon1,double lat2,double lon2) {
int R = 6371; //Earth Radius
double dLat = degreeToRadiant(lat2-lat1);
double dLon = degreeToRadiant(lon2-lon1);
double a =
Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(degreeToRadiant(lat1)) * Math.cos(degreeToRadiant(lat2)) *
Math.sin(dLon/2) * Math.sin(dLon/2)
;
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
return R * c; //Distance in km
}

我的表/实体包含一列用于经度,另一列用于纬度。

另一个问题,是否有可能像之前所说的那样用 spring data jpa 解决这个问题?

我尝试将 Java 代码转换为 Mysql,但距离太远。

SELECT name, (6371 * (
2 * ATAN2(
SQRT(
SIN(RADIANS((48.3069400-latitude))/2) * SIN(RADIANS((48.3069400-latitude)/2)) +
COS(RADIANS(latitude)) * COS(RADIANS(48.3069400)) * SIN(RADIANS((48.3069400-longitude)/2)) *
SIN(RADIANS((48.3069400-longitude)/2))
),SQRT(
1-(SIN(RADIANS((48.3069400-latitude))/2) * SIN(RADIANS((48.3069400-latitude)/2)) +
COS(RADIANS(latitude)) * COS(RADIANS(48.3069400)) * SIN(RADIANS((48.3069400-longitude)/2)) *
SIN(RADIANS((48.3069400-longitude)/2)))
)
)
)) as distance FROM event

最佳答案

在 MySQL 5.7.x 中,恕我直言,最有效的方法是使用几何函数:

SELECT st_distance_sphere( POINT( lat1, long1) , POINT(lat2, long2 ));

您将获得以米为单位的距离。

在 MariaDB 上 st_distance( ... ) 将返回类似的结果。

关于java - 计算两个 long/lat 之间的距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46295612/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com