0

I'm using the Geocoder gem to calculate the distance between some locations and the users location. I'm also manually plugging in the coordinates to measure the distance and the values are totally off.

Inside the serialized model:

attribute :distance_to_user do
  if @user_location.present?
    locale = @language.locale
    units = (I18n.t "distance.thousand.other", default: "km").to_sym
    distance = @object.distance_to(@user_location, units)
    converted_distance = LocationsHelper.convert_distance(locale, distance)
    ActionController::Base.helpers.number_to_human(converted_distance, units: :distance, format: "%n%u")
  end
end

LocationHelper

def convert_distance(locale, distance)
  return distance if locale.eql?("en-US")
  distance * 1000
end

@user_location returns the correct coordinate for the user and @object has the correct coordinates for the items location but the distance calculated is totally off.

Doolan
  • 1,293
  • 1
  • 13
  • 28
  • What do you mean by _totally of_? Can you give an example? Two locations, the result you get and the expected result? – spickermann Feb 10 '21 at 18:39
  • @spickermann sure, `@user_location = [37.6611464, -122.06680220000001]` and `@object = [37.7950691, -122.2777955]`. `distance` is being returned as `6715.596349892686` which is then converted to 6.71 mi but the actual distance should be ~15 mi – Doolan Feb 10 '21 at 19:45

1 Answers1

0

Not sure why @object.distance_to() was giving me the wrong distance but I ended up going with Geocoder::Calculations.distance_between() and that gave me the correct value.

Doolan
  • 1,293
  • 1
  • 13
  • 28