Order by nearest - PostGIS, GeoRuby, spatial_adapter

后端 未结 6 2033
醉酒成梦
醉酒成梦 2021-02-06 04:03

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

相关标签:
6条回答
  • 2021-02-06 04:30

    Look at the ST_Distance documentation in PostGIS.

    0 讨论(0)
  • 2021-02-06 04:32

    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..

    0 讨论(0)
  • 2021-02-06 04:33

    To wrap this up, with everyone's help I've got it working how I wanted:

    order("ST_Distance(items.position, ST_GeomFromText('POINT (#{current_location.y} #{current_location.x})', #{SRID}))")
    
    0 讨论(0)
  • 2021-02-06 04:40

    Just in case somebody stumbles upon this issue in rails 4. I am using rgeo gem and this works for me

    scope :closest, ->(point) { order("ST_Distance(lonlat, ST_GeomFromText('#    {point.as_text}', #{SRID}))").limit(5) }
    
    0 讨论(0)
  • 2021-02-06 04:46

    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

    0 讨论(0)
  • 2021-02-06 04:50

    To get the 5 closest:

    SELECT * FROM your_table 
    ORDER BY ST_Distance(your_table.geom, ST_Geomfromtext(your point as wkt)) 
    limit 5;
    

    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:

    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;
    

    /Nicklas

    0 讨论(0)
提交回复
热议问题