PostGIS:如何找到与给定集合最接近的 N 组点?

Til*_*ilo 6 gis postgresql postgis ruby-on-rails geospatial

我正在使用 PostGIS/Rails 并且有一组带有地理位置的点。

class DataSet < ActiveRecord::Base  # these are the sets containing the points
  has_many :raw_data
  # attributes: id , name
end

class RawData < ActiveRecord::Base  # these are the data points
  belongs_to :data_set
  # attributes: id, location which is "Point(lon,lat)"
end
Run Code Online (Sandbox Code Playgroud)

对于给定的一组点,我需要找到 N 个最近的组和它们的距离;

或者: 对于给定的最大距离和一组点,我需要找到 N 个最近的组。

使用 PostGIS 执行此操作的最佳方法是什么?

我的版本是带有 PostGIS 2.1.2 的 PostgreSQL 9.3.4

Ale*_*ros 7

关于如何在 PostGIS 中找到 N-最近邻的答案在这里给出:

最近邻居的 Postgis SQL

总结那里的答案:

您需要为您的点创建一个几何对象。如果使用纬度、经度,则需要使用4326。

UPDATE season SET geom = ST_PointFromText ('POINT(' || longitude || ' ' || latitude || ')' , 4326 ) ;
Run Code Online (Sandbox Code Playgroud)

然后在 geom 字段上创建索引

CREATE INDEX [indexname] ON [tablename] USING GIST ( [geometryfield] ); 
Run Code Online (Sandbox Code Playgroud)

然后你得到 kNN 邻居:

SELECT *,ST_Distance(geom,'SRID=4326;POINT(newLon newLat)'::geometry) 
FROM yourDbTable
ORDER BY
yourDbTable.geom <->'SRID=4326;POINT(newLon newLat)'::geometry
LIMIT 10;
Run Code Online (Sandbox Code Playgroud)

其中 newLon newLat 是查询点坐标。

此查询将利用 gist 索引 ( http://workshops.boundlessgeo.com/postgis-intro/knn.html )的 kNN 功能。

返回的距离仍然以度为单位,而不是米(投影 4326 使用度)。

要解决此问题:

SELECT *,ST_Distance(geography(geom),ST_GeographyFromText('POINT(newLon newLat)') 
FROM yourDbTable
ORDER BY
yourDbTable.geom <->'SRID=4326;POINT(newLon newLat)'::geometry
LIMIT 10;
Run Code Online (Sandbox Code Playgroud)

当您计算 ST_distance 时,请使用地理类型。那里的距离总是以米为单位:

http://workshops.boundlessgeo.com/postgis-intro/geography.html

所有这些功能可能需要最新的 Postgis 版本 (2.0+)。我不确定。

检查此以供参考https://gis.stackexchange.com/questions/91765/improve-speed-of-postgis-nearest-neighbor-query/

编辑。这涵盖了一点的必要步骤。对于点集:

SELECT n1.*,n2.*, ST_Distance(n1.geom,n2.geom) 
FROM yourDbTable n1, yourDbTable n2
WHERE n1.setId=1 AND n1.setId=2 //your condition here for the separate sets
AND n1.id<>n2.id // in case the same object belong to 2 sets
ORDER BY n1.geom <->n2.geom
LIMIT 20;
Run Code Online (Sandbox Code Playgroud)