0

I am using the geocoder gem to implement geolocation in my rails app. I am geolocating by address. The users are displayed properly according to location on the map but the distance away is incorrect. When the user index is displayed following the search the users are all set to 250.00 to 253 miles away even though they should all be 1 or 3 miles away from the address I have saved as a user. Any reason why this would be the case and how I can fix it? Also, when I attempt to search for the users nearby, all the users are being picked up, I have 100 miles declared in the index controller and if I put a user 1000 miles away they are picked up as well. How would you set it so that only users within the 100 miles radius are picked up? Any help would be greatly appreciated, thanks!

schema.rb

  create_table "users", force: true do |t|
    t.string   "address"
    t.string   "city"
    t.string   "state_province"
    t.float    "latitude"
    t.float    "longitude"
    t.string   "country"

user.rb

geocoded_by :full_address
after_validation :geocode

def full_address
    "#{self.address}, #{self.city}, #{self.state_province}, #{self.country}"
end

user_controller.rb

  def index
    if  params[:city_search]
      @users = User.near(params[:city_search],100)
      @users = User.all_except(current_user)

index.html.erb

<% if @users.count > 1 %>

     <%= "is #{user.distance_to(params[:city_search]).round(2)} miles away." %> 

<% end %>


<%= javascript_tag do %>

<% if params[:city_search] != "" %>

  var latitude = <%= @users.first.latitude %>;
  var longitude = <%= @users.first.longitude %>;
  var showMarker = false;

  var coords = <%= raw @users.map{|user| {latitude: user.latitude, longitude: user.longitude, id: user.id}}.to_json %>; 

<% end %> 

<% end %>
achilles77
  • 325
  • 2
  • 3
  • 11
  • Are you sure the method `distance_to` returns a value in miles? – Jake Smith Dec 28 '14 at 19:46
  • yes it is displaying the 253 miles away – achilles77 Dec 28 '14 at 19:56
  • i can get the correct number in my console however, when i type User.nearbys(10) it displays the users and provides the proper distance under the distance column within each of those users, for exapmple distance: 3 miles or distance: .8 miles. I am just trying to show that in my view – achilles77 Dec 28 '14 at 19:58
  • You use `User.near` in your code above. Not `User.nearbys`. Also you typed miles in a string outside of the call to `distance_to`. Does the gem's documentation say that method returns miles? – Jake Smith Dec 28 '14 at 20:01
  • Yeah User.nearbys is not working in my code. The gems documentation returns miles by default. – achilles77 Dec 28 '14 at 20:04
  • http://www.rubydoc.info/github/alexreisner/geocoder/master/Geocoder/Store/Base:distance_to – Jake Smith Dec 28 '14 at 20:06
  • I couldn't find where it specified the miles as default. Maybe try passing in the miles symbol? – Jake Smith Dec 28 '14 at 20:06

0 Answers0