mysqlrubyactiverecordgeolocationrails-geocoder

ActiveRecord query for posts within a certain radius using geocoder?


I have the following MYSQL table schema which comprises of posts with their latitude and longtitude recorded:

+------------+--------------+------+-----+---------+----------------+
| Field      | Type         | Null | Key | Default | Extra          |
+------------+--------------+------+-----+---------+----------------+
| id         | int(11)      | NO   | PRI | NULL    | auto_increment |
| user       | varchar(128) | NO   |     | NULL    |                |
| content    | varchar(512) | NO   |     | NULL    |                |
| timestamp  | varchar(128) | NO   |     | NULL    |                |
| longtitude | double       | NO   |     | NULL    |                |
| latitude   | double       | NO   |     | NULL    |                |
+------------+--------------+------+-----+---------+----------------+

With the geocoder gem, I am able to use a method to figure out the distance between two lat, long coordinates.

find the distance between two arbitrary points
Geocoder::Calculations.distance_between([47.858205,2.294359], [40.748433,-73.985655])
 => 3619.77359999382 # in configured units (default miles)

I would like to retrieve a set of records from the table. I know I can get batches of 10 records, sorted by time using the following query:

  record = Post.order(:timestamp).offset(10 * @var.to_i).first(10)

How can I modify this query such that I get all post within a certain radius? I.e. only show posts which have their coordinates within 5km of the current user's location?

I am using Sinatra instead of Rails if it matters.


Solution

  • You could use the near method provided by geocoder :

    Post.near([lat, lon], 5)
    

    As stated in their documentation, you will need to add this to your model :

    extend Geocoder::Model::ActiveRecord
    

    Reference : https://github.com/alexreisner/geocoder#for-activerecord-models