如何计算与经纬度的距离

How to calculate distance from latitude and longitude

本文关键字:经纬度 距离 计算 何计算      更新时间:2023-09-26

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

create table doksyndm (
id serial primary key,
readingtime timestamp with time zone not null,
latitude float,
longitude float
 );
使用导航器从浏览器保存

点。javascript中的地理位置调用。

如何从这些数据计算路由长度?路线不超过300公里,所以点之间的直线长度可以相加。它应该在Postgres 9.1和更新的版本中工作。

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

计算google maps V3中两点之间的距离的答案如何在生产语言中实现。

它们使用SQL中不可用的for循环。也许SUM()与窗口函数可以用来实现这一点?

我假设您想要从最早的点到下一个最早的点的距离,等等…

从Postgresql 9.3开始,有一个使用横向连接的优雅解决方案。

首先,安装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