Reputation: 5367
I am currently porting a PHP application to Rails. I need to calculate nearest venues from a given latitude and longitude.
In my PHP application, I had this MySQL query (clubs are the venues I'm talking about):
SELECT cl.*, c.id, c.slug AS city_slug,
(3959 * acos(cos(radians(:lat)) * cos(radians(cl.lat)) * cos(radians(cl.lng) - radians(:lng)) + sin(radians(:lat)) * sin(radians(cl.lat))))
AS distance
FROM club cl, city c
WHERE cl.published = 1
AND c.id = cl.city_id
AND cl.id <> :club_id
AND cl.deleted = 0
ORDER BY distance
LIMIT 0,10
As you can see, the calculations are being made in the database layer and I would like it to stay like that.
How can I achieve this with Rails, ActiveRecord and PostgreSQL?
Upvotes: 2
Views: 3047
Reputation: 191
One possibility to do that is use Geokit gem:
https://github.com/geokit/geokit-rails
they provides an scope to find closest record from coordinates:
Club.closest(origin: [@lat,@long])
in documentation you can find another examples and options.
Upvotes: 2