Search code examples
sqlruby-on-railsrubyrails-geocoder

Using Ruby Geocoder for retrieving nearby users and return distance


Is it possible to use Geocoder for retrieving, say, nearby users within a certain radius, and make it return the result of the distance calculation without having to repeat for display?

For example, say we use this (in a Rails application):

User.near(@me, 10, units: :km)

It will return an ActiveRecord::Relation with all the users that are within 10 kilometres of user @me.

If I now want to display a list with all the returned users and their distance to @me, do I need to actually recompute the distances one by one using distance_to, or is there are a way to make Geocoder return the computed distances in an added model attribute (for example)?


Solution

  • When you run a location-aware query the returned objects have two attributes added to them:

    User.near(@me, 10, units: :km).each do |user|
      puts "#{user.name} is #{user.distance} clicks to the #{user.bearing}"
    end