【发布时间】:2011-07-03 22:55:06
【问题描述】:
我正在尝试进行订单查询,以查找最接近 current_user 的记录。
我知道两点之间的距离是:current_location.euclidean_distance(@record.position)
如何将其用于 PostGIS(或 active_record/spatial_adapter)查询?
【问题讨论】:
标签: ruby-on-rails gis postgis
我正在尝试进行订单查询,以查找最接近 current_user 的记录。
我知道两点之间的距离是:current_location.euclidean_distance(@record.position)
如何将其用于 PostGIS(或 active_record/spatial_adapter)查询?
【问题讨论】:
标签: ruby-on-rails gis postgis
查看 PostGIS 中的 ST_Distance 文档。
【讨论】:
如果您不需要使用 PostGIS,geo-kit 可以使用 google 或 yahoo(我只使用过 Google)完美地做到这一点,并且在您的查询中您可以按距离排序,这太棒了..
【讨论】:
要获得最接近的 5 个:
SELECT * FROM your_table
ORDER BY ST_Distance(your_table.geom, ST_Geomfromtext(your point as wkt))
limit 5;
如果您有一个大数据集,并且知道您不想搜索比 1 公里更远的地方,那么如果您这样做,查询的效率会更高:
SELECT * FROM your_table
WHERE ST_DWithin(your_table.geom, ST_Geomfromtext(your point as wkt, 1000)
ORDER BY ST_Distance(your_table.geom, ST_Geomfromtext(your point as wkt))
limit 5;
/尼克拉斯
【讨论】:
.order('ST_Distance(items.position, #{current_location})')
.order("#current_location")
ST_Distance 的调用中的items 指的是具有地理编码元素的数据库表的名称。
总结一下,在大家的帮助下,我已经完成了我想要的工作:
order("ST_Distance(items.position, ST_GeomFromText('POINT (#{current_location.y} #{current_location.x})', #{SRID}))")
【讨论】:
如果您真的想从字面上找到最接近 current_user 的 5 条记录,请考虑邻域搜索,它由 PostGIS 2.0 中的 KNN 索引支持(请参阅 '' 运算符):
SELECT * FROM your_table ORDER BY your_table.geom <-> ST_Geomfromtext(your point as wkt, 1000) LIMIT 5
【讨论】:
以防万一有人在 rails 4 中偶然发现了这个问题。 我正在使用 rgeo gem,这对我有用
scope :closest, ->(point) { order("ST_Distance(lonlat, ST_GeomFromText('# {point.as_text}', #{SRID}))").limit(5) }
【讨论】:
lonlat
SRID 的值应该是一个整数,该整数指向您用来计算距离的坐标系的众所周知的ID,这可能会有所帮助。您很可能希望使用 ID 4326 的地球的Geodesic coordinate system。