7
votes

I'm having a slight issue trying to display certain locations based on proximity to a user. In my controller I have this:

  if User.find(current_user)
    @user = User.find(current_user)
    @locations = Location.near(params[:latitude => @user.latitude, :longitude => @user.longitude], 50, :order => :distance)
  end

Users have a latitude and longitude stored. I'm thinking I've not got the right parameters in the Location.near line, but I can't figure out what they should be.

Any help would be appreciated.

Cheers!

2
when ever i try to use :order => :distance it show me error cant convert distance into to_f - Ayaz Ahmad Tarar

2 Answers

8
votes

Lets try re-writing that a bit, current_user should already be set, no need for calling User.find. Then it looks like you can pass lat,long as an array

 @locations = Location.near([current_user.latitude, current_user.longitude], 50, :order => :distance)

http://railscasts.com/episodes/273-geocoder

http://www.rubygeocoder.com/

https://github.com/alexreisner/geocoder (check the readme)

2
votes

You can define the distance that you want search, remember pass the unit, too:

@locations = Location.near([current_user.latitude, current_user.longitude], 50, units: :km)