Calculate distance between two coordinates using ActiveRecord Arel

If you had to calculate the distance between two coordinates you probably found several different ways using the haversine formula:

The haversine formula determines the great-circle distance between two points on a sphere given their longitudes and latitudes. Important in navigation, it is a special case of a more general formula in spherical trigonometry, the law of haversines, that relates the sides and angles of spherical triangles.

And probably you saw many variations of SQL query like this:

In practice some_latitude and some_longitude would be entered in your query as the search parameters and the lat/lng represents the value already in the database. The average radius of the Earth is 6,371 km (3,960 miles). Multipling the result of the formula by 6371 is used to make sure the results are in kilometers.

If you are using similar SQL multiple times on your code or maybe if you donâ€™t like to write raw SQL on your ruby application, here is a small activerecord and arel helper that can be useful to compose SQL query.

Here are a few examples of how to use to build your queries:

List the 10 closest addresses of a coordinate with the distance in meters.

Get addresses that are at least 1km from a given coordinate.

MySQL added a few spatial convenience functions since version 5.7.6. And one of those convenience functions is ST_Distance_Sphere, which allows one to calculate the (spherical) distance between two points. And it makes things much simpler.

PostgreSQL has also a great extension named PostGIS that provides spatial objects. Strongly recommend the use.

If you are looking for more advanced queries or a complete geocode solution take a look at the geocoder gem. This gem adds several scopes to the activerecord according to the examples in the documentation.