ruby-on-railsrubygoogle-mapsgeocodinggeokit

Calculating the distance between 2 latitude and longitude locations in a rails project


I am using the

geokit-rails

gem to calculate the distance between 2 objets which contain latitude and longitude fields: https://github.com/geokit/geokit-rails

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?


Solution

  • This was complete user error. The code I have posted in this question is actually entirely correct.

    Due to several underlying issues in the models and controllers the values in latitude and longitude columns were not being persisted.

    All fixed :)