Search code examples
ruby-on-railsruby-on-rails-3ruby-on-rails-3.2rails-geocoder

How to find the users within 10miles using latitude and longitude of the user in rails?


I have latitude and longitude of all the user. I have to find the user who is near to me (around 10 miles) from my current latitude and longitude. And i have to give it as response in json. I have tried to configure geokit gem for this but it showed me some error like

WARNING: geokit-rails requires the Geokit gem. You either don't have the gem installed,
or you haven't told Rails to require it. If you're using a recent version of Rails: 
  config.gem "geokit" # in config/environment.rb
and of course install the gem: sudo gem install geokit

so i have moved to geocoder. What should i do with this geocoder for finding users with the above said conditions? please help me.


Solution

  • class User < ActiveRecord::Base
      geocoded_by :address
    
      after_validation :geocode, if: :address_changed?
    end
    
    User.near([latitude, longitude], 10).to_json
    
    # or even simpler since current_user is a geocoded object (i.e has lat/long)
    
    User.near(current_user, 10).to_json