0

I try to use PostGIS in Rails and write my first request. I would like have :

  • The nearest points of another point (but without this point)
  • The name and the distance between them both

In my model I have write this scope :

 scope :close_to, -> (latitude, longitude, distance_in_m = 1) {
  where(%{
  ST_Distance(lonlat, 'POINT(%f %f)') < %d
 } % [longitude, latitude, distance_in_m * 1000])
}

How can I get the distance ?

Vince
  • 20,017
  • 15
  • 45
  • 64
Ben
  • 141
  • 4

1 Answers1

0

Search for the Nearest Neighbor in postgis is a well know problem solved multiple times in stack overflow and the "internet", like:

In it's more basic form the query can be written like this:

SELECT name, gid, ST_Distance(geom, st_setsrid(st_makepoint(-90,40),4326))
FROM geonames
ORDER BY geom <-> st_setsrid(st_makepoint(-90,40),4326)
LIMIT 1;

but it can be improved depending on your use case.

Francisco Puga
  • 4,618
  • 21
  • 40