Sha256: de8cbc38398db1acd2438d51a9931303f31b2cad067104c26e8deee112f5174c

Contents?: true

Size: 1.7 KB

Versions: 17

Compression:

Stored size: 1.7 KB

Contents

module Graticule
  module Distance

    #
    # The Spherical Law of Cosines is the simplist though least accurate distance
    # formula (earth isn't a perfect sphere).
    #
    class Spherical < DistanceFormula

      # Calculate the distance between two Locations using the Spherical formula
      #
      #   Graticule::Distance::Spherical.distance(
      #     Graticule::Location.new(:latitude => 42.7654, :longitude => -86.1085),
      #     Graticule::Location.new(:latitude => 41.849838, :longitude => -87.648193)
      #   )
      #   #=> 101.061720831853
      #
      def self.distance(from, to, units = :miles)
        from_longitude   = deg2rad(from.longitude)
        from_latitude    = deg2rad(from.latitude)
        to_longitude  = deg2rad(to.longitude)
        to_latitude   = deg2rad(to.latitude)

        Math.acos(
            Math.sin(from_latitude) *
            Math.sin(to_latitude) +

            Math.cos(from_latitude) * 
            Math.cos(to_latitude) *
            Math.cos(to_longitude - from_longitude)
        ) * EARTH_RADIUS[units.to_sym]
      end

      def self.to_sql(options)
        options = {
          :units => :miles,
          :latitude_column => 'latitude',
          :longitude_column => 'longitude'
        }.merge(options)
        %{(ACOS(
            SIN(RADIANS(#{options[:latitude]})) *
            SIN(RADIANS(#{options[:latitude_column]})) +
            COS(RADIANS(#{options[:latitude]})) *
            COS(RADIANS(#{options[:latitude_column]})) *
            COS(RADIANS(#{options[:longitude_column]}) - RADIANS(#{options[:longitude]}))
          ) * #{Graticule::Distance::EARTH_RADIUS[options[:units].to_sym]})
        }.gsub("\n", '').squeeze(" ")
      end
  
    end
  end
end

Version data entries

17 entries across 17 versions & 3 rubygems

Version Path
GUI-graticule-0.2.7.2 lib/graticule/distance/spherical.rb
GUI-graticule-0.2.7.3 lib/graticule/distance/spherical.rb
GUI-graticule-0.2.7.4 lib/graticule/distance/spherical.rb
GUI-graticule-0.2.7.5 lib/graticule/distance/spherical.rb
GUI-graticule-0.2.7.6 lib/graticule/distance/spherical.rb
norman-graticule-0.2.7 lib/graticule/distance/spherical.rb
graticule-0.2.1 lib/graticule/distance/spherical.rb
graticule-0.1.2 lib/graticule/distance/spherical.rb
graticule-0.1.3 lib/graticule/distance/spherical.rb
graticule-0.2.0 lib/graticule/distance/spherical.rb
graticule-0.2.6 lib/graticule/distance/spherical.rb
graticule-0.2.5 lib/graticule/distance/spherical.rb
graticule-0.2.3 lib/graticule/distance/spherical.rb
graticule-0.2.4 lib/graticule/distance/spherical.rb
graticule-0.2.2 lib/graticule/distance/spherical.rb
graticule-0.2.8 lib/graticule/distance/spherical.rb
graticule-0.2.7 lib/graticule/distance/spherical.rb