geokit / geokit-rails

Official Geokit plugin for Rails/ActiveRecord. Provides location-based goodness for your Rails app. Requires the Geokit gem.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

distance_to does not appear to calculate distance between 2 objects.

renegadeandy opened this issue · comments

I have a Leg object - which contains both 1 origin object and 1 destination object.

Origin looks like this :


class Origin < ApplicationRecord
  belongs_to :leg

  validates :name, presence: true
  validates :longitude, presence: true
  validates :latitude, presence: true
  validates :type, presence: true
  
  acts_as_mappable :default_units => :miles,
                   :default_formula => :sphere,
                   :distance_field_name => :distance,
                   :lat_column_name => :latitude,
                   :lng_column_name => :longitude

end

The destination model looks like this:

class Destination < ApplicationRecord
  belongs_to :leg

  validates :name, presence: true
  validates :longitude, presence: true
  validates :latitude, presence: true
  validates :type, presence: true

  acts_as_mappable :default_units => :miles,
                   :default_formula => :sphere,
                   :distance_field_name => :distance,
                   :lat_column_name => :latitude,
                   :lng_column_name => :longitude
end

Then I call this line in my Leg object, to get a distance between an origin and destination. Both the origin and destination records exist - with valid latitude and longitude values in the DB.

def distance
  	if(origin.present? && destination.present?)
  		distance = origin.distance_from(destination, :units=>:miles)
  		puts "distance in leg is:"+distance.to_s
  		return distance
  	else
  		return 0
  	end
  end

The distance returned is always 0.0, despite using valid origin / destination objects which have appropriate values in the latitude and longitude columns.

Am I using this wrong? Can anybody help?

This was actually user error - the code shown here works entirely. Apologies for wasting any time. This question ties up to : https://stackoverflow.com/questions/44535413/calculating-the-distance-between-2-latitude-and-longitude-locations-in-a-rails-p/44610235#44610235