我有以下表格
create table places(lat_lng point, place_name varchar(50));
insert into places values (POINT(-126.4, 45.32), 'Food Bar');
如何查询距离特定经纬度附近的所有位置?
已安装gis。
我有以下表格
create table places(lat_lng point, place_name varchar(50));
insert into places values (POINT(-126.4, 45.32), 'Food Bar');
如何查询距离特定经纬度附近的所有位置?
已安装gis。
如果你确实想使用PostGIS:
create table places(
lat_lng geography(Point,4326),
place_name varchar(50)
);
-- Two ways to make a geography point
insert into places values (ST_MakePoint(-126.4, 45.32), 'Food Bar1');
insert into places values ('POINT(-126.4 45.32)', 'Food Bar2');
-- Spatial index
create index places_lat_lng_idx on places using gist(lat_lng);
现在要查找1公里(或1000米)内的所有位置:
select *, ST_Distance(lat_lng, ST_MakePoint(-126.4, 45.32)::geography)
from places
where ST_DWithin(lat_lng, ST_MakePoint(-126.4, 45.32)::geography, 1000)
order by ST_Distance(lat_lng, ST_MakePoint(-126.4, 45.32)::geography);
select *
from places
where lat_lng <-> POINT(-125.4, 46.32) < 1
order by lat_lng <-> POINT(-125.4, 46.32)
CREATE INDEX ON table_name USING GIST(location);
GiST索引能够优化“最近邻”搜索:
SELECT * FROM table_name ORDER BY location <-> point '(-74.013, 40.711)' LIMIT 10;
注意:点的第一个元素是经度,第二个元素是纬度。
ST_MakePoint
强制转换为geography
吗?我遇到了一个问题,当我没有进行类型转换时,ST_Distance 返回了错误的结果。ST_distance 接受 geometry 类型,而 ST_MakePoint 已经返回了 geometry 类型。那么到底发生了什么事情呢? - Bibhas Debnath