gpt4 book ai didi

sql - 查询SQL数据库,如何获取用户位置附近的最近点?

转载 作者:搜寻专家 更新时间:2023-10-30 23:02:55 25 4
gpt4 key购买 nike

在过去的一个 Java 项目中,我编写了以下代码来获取到指定位置(50 公里以内)的最近点:

// user position
double myLatG = myLat * Math.PI / 180;
double myLonG = myLon * Math.PI / 180;

// loop on sqlite database that contains all points
while (cur.moveToNext()) {
double destLatG = cur.getDouble(0) * Math.PI / 180;
double destLonG = cur.getDouble(1) * Math.PI / 180;
double phi = Math.abs(myLonG - destLonG);
double distance = (Math.acos(Math.cos(phi) * Math.cos(myLatG) * Math.cos(destLatG) + Math.sin(myLatG) * Math.sin(destLatG))) * 6387;

if (distance <= 50) {
// my code
}
}

现在我想在 SQL 数据库 上做同样的事情,我的意思是在 50 公里范围内找到与提供的纬度和经度最近的点。所以将上述算法应用于数据库(Postgres)。是否可以使用任何 SQL 查询获得相同的结果?

最佳答案

你可以试试

SELECT lat, lon 
FROM
(
SELECT lat,
lon,
frml(lat, lon, :mylat, :mylon) AS distance,
FROM table_all_points
) distance_table
WHERE distance <= 50

其中 table_all_points 是包含所有点的数据库表,而 :mylat 和 :mylon 是您的输入参数。

将 frml(lat,lon,:mylat,:mylon) 替换为一个单行公式,您可以在其中计算与给定的纬度、经度、mylat 和 mylon 值的距离。我认为 frml(lat, lon, :mylat, :mylon) 必须是

acos(cos(@(:mylon * pi()/180- lon * pi()/180)) * cos(:mylat * pi()/180) * cos(lat * pi()/180) + sin(:mylat * pi()/180) * sin(lat * pi()/180))) * 6387;

这里列出了可以与 postgres 一起使用的数学函数: http://www.postgresql.org/docs/7.4/static/functions-math.html

如果您不想使用单行公式,您可以添加另一个中间表,但我不确定它是否更有效。

关于sql - 查询SQL数据库,如何获取用户位置附近的最近点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30105013/

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