按最近排序 - PostGIS、GeoRuby、spatial_adapter
我正在尝试执行一个订单查询来查找最接近 current_user 的记录。
我知道两点之间的距离是:current_location.euclidean_distance(@record.position)
如何将其处理到 PostGIS(或 active_record/spatial_adapter)查询中?
I'm trying to do an order query that finds records nearest to the current_user.
I know the distance between the two points is: current_location.euclidean_distance(@record.position)
How can I work this into a PostGIS (or active_record/spatial_adapter) query?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
要获得最近的 5 个:
如果您有一个大数据集并且知道您不想搜索超过 1 公里的距离,那么如果您这样做,查询将会更有效:
/Nicklas
To get the 5 closest:
If you have a big dataset and know that you don't want to search further than , say 1 km, the query will be more efficient if you do:
/Nicklas
以防万一有人在 Rails 4 中偶然发现这个问题。
我正在使用 rgeo gem,这对我有用
Just in case somebody stumbles upon this issue in rails 4.
I am using rgeo gem and this works for me
总而言之,在大家的帮助下,我已经按照我想要的方式工作了:
To wrap this up, with everyone's help I've got it working how I wanted:
如果您确实想查找距离当前用户最近的 5 条记录,请考虑邻域搜索,PostGIS 2.0 中的 KNN 索引支持这种搜索(请参阅“<->”运算符):
SELECT * FROM your_table ORDER BY your_table .geom <-> ST_Geomfromtext(您的点为 wkt,1000)LIMIT 5
If you really want to find literally the 5 records nearest to the current_user, consider neighborhood search, which is supported by KNN index in PostGIS 2.0 (see '<->' operator):
SELECT * FROM your_table ORDER BY your_table.geom <-> ST_Geomfromtext(your point as wkt, 1000) LIMIT 5
查看 PostGIS 中的 ST_Distance 文档。
Look at the ST_Distance documentation in PostGIS.
如果你不需要使用 PostGIS,geo-kit 使用 google 或 yahoo(我只使用过 Google)可以完美地完成此操作,并且在你的查询中你可以按距离排序,这太棒了..
If you dont NEED to use PostGIS, geo-kit does this perfectly using google or yahoo (I've only used Google) and in your queries you can sort by distance, its awesome..