Monthly Archives: October 2016

Adding a radius search to your Ruby on Rails 5 application and PostgreSQL

Recently one of my project need to create a functionality for location based search. I choose PostgreSQL as database because I want to use some power of PostgreSQL.

So I want to create a functionality where I can send three param in a PostgreSQL and this database will return me location within this radius.  So I want to search what locations are within X meters of these coordinates.

Using PostgreSQL is lot easier.

First you need to enable some plugin for PostgreSQL.

  CREATE EXTENSION earthdistance;

Now you can run query like:

SELECT \"franchises\".* FROM \"franchises\" WHERE (earth_box(ll_to_earth(40.810649, -73.598605), 2000) @> ll_to_earth(latitude, longitude))

You can also create a scope in rails model.

scope :within_radius, lambda {|latitude, longitude, metres| where("earth_box(ll_to_earth(?, ?), ?) @> ll_to_earth(latitude, longitude)", latitude, longitude, metres) }

And that’s it. You can call

  Franchise.within_radius(43.6422125, -79.3744256, 5000) 

and you’ll have a list of franchises within 5 km of NY.

Happy coding 🙂