公里距离
来自 PostgreSQL Wiki
跳转到导航跳转到搜索
获取两点 (lat1, long1, lat2, long2) 之间的距离,并考虑地球曲率。注意,plperlu 函数并不精确,但应该非常接近。
此示例使用 contrib 模块“Earthdistance”和“Cube”,产生的结果与下面的 Math::Trig 函数几乎相同
select ROUND( ('(33.0, 97.1)'::point <@> '(24.0, 88.6)')::NUMERIC * 1.609344 ) as km;
如果您无法或不想安装 earthdistance 和 cube contrib 模块,可以编写 plperlu 函数以获得类似的结果
create or replace function distance_in_km (numeric,numeric,numeric,numeric) returns numeric as $body$
use strict;
use Math::Trig qw(great_circle_distance deg2rad);
# from https://perldoc.perl5.cn/Math/Trig.html
my $lat1 = shift(@_);
my $lon1 = shift(@_);
my $lat2 = shift(@_);
my $lon2 = shift(@_);
#elog WARNING, "$lat1, $lon1, $lat2, $lon2\n";
# Notice the 90 - latitude: phi zero is at the North Pole.
sub NESW { deg2rad($_[0]), deg2rad(90 - $_[1]) }
my @L = NESW( $lat1, $lon1 );
my @T = NESW( $lat2, $lon2 );
my $km = great_circle_distance(@L, @T, 6378);
return $km;
$body$ language plperlu strict security definer;
select ROUND(km) as km from distance_in_km(33.0,97.1,24.0,88.6) as km; km ----- 945
由 bricklen 编写,欢迎您进行修正或增强!