javascript - 如何根据经纬度计算距离

标签 javascript sql postgresql geolocation plpgsql

在 Postgres 9.1+ 数据库中包含路由点:

create table doksyndm (
id serial primary key,
readingtime timestamp with time zone not null,
latitude float,
longitude float
 );

使用来自 javascript 的 navigator.geolocation 调用从浏览器保存点。

如何根据这些数据计算路线长度? 路线小于 300 公里,因此点之间的直线长度可以相加。 它应该适用于 Postgres 9.1 和更新版本。

结果应该是一个数字,以千米为单位的点之间的总距离。 如果合理,可以重构数据库和javascript代码发送点。

Calculate distance between two points in google maps V3 中的答案如何用过程语言实现这一点。

它们使用 SQL 中不可用的 for 循环。带有窗口函数的 Maby SUM() 可以用来实现这个吗?

最佳答案

我假设您想要从最早点到下一个最早点的距离,依此类推...

从 Postgresql 9.3 开始,有一个使用 lateral join 的优雅解决方案。 .

首先,安装 postgis 扩展,这样您就可以使用它的距离功能:

CREATE EXTENSION POSTGIS;

现在查询:

 SELECT SUM(st_distance(st_point(a.longitude,a.latitude)::geography,
                       st_point(b.longitude,b.latitude)::geography)
            ) / 1000 AS distance_km FROM doksyndm a
LEFT JOIN LATERAL
 (SELECT * FROM doksyndm WHERE readingtime > a.readingtime limit 1) b ON TRUE;

此查询使用 distinct on应该适用于所有版本:

 SELECT SUM (st_distance(st_point(alon,alat)::geography,
              st_point(blon,blat)::geography))/1000 as distance_km FROM
    ( select distinct ON (a.readingtime) a.readingtime, 
                                        a.latitude as alat,
                                        a.longitude as alon, 
                                        b.latitude as blat ,
                                        b.longitude as blon
    FROM doksyndm a inner join doksyndm b on a.readingtime < b.readingtime
 ORDER by a.readingtime,b.readingtime) x

关于javascript - 如何根据经纬度计算距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40514702/

相关文章:

sql - 记录之间流逝的平均时间

python-3.x - pywintypes.com_error : (-2147024882, 'Not enough memory resources are available to complete this operation.',无,无)

javascript - 检查 moment.js 中的时间格式是否有效

javascript - 尝试从 JavaScript 读取本地文件时访问被拒绝

sql - 如何检查数据库的架构

sql - 在 UNION ALL View 创建中使用 JOIN

javascript - 原版 JS 文件的 Github secret

javascript - 使用 CSS 样式的自定义光标 - html/css - javascript

c# - 将 Oracle DB 配置为默认采用双字节字符集

java - 在 Android 中调用游标时收到 NullPointerException