Class: GIS::Distance

Inherits:
Object
  • Object
show all
Defined in:
lib/gis/distance.rb

Overview

The Distance class encapsulates methods related to geographic distance.

Defined Under Namespace

Classes: Error

Constant Summary collapse

VERSION =

The version of the gis-distance library

'1.0.0'

Instance Method Summary collapse

Constructor Details

#initialize(latitude1, longitude1, latitude2, longitude2) ⇒ Distance

Create a new GIS::Distance object using the two sets of coordinates that are provided.

If invalid coordinates are provided a GIS::Distance::Error is raised.



16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/gis/distance.rb', line 16

def initialize(latitude1, longitude1, latitude2, longitude2)
   validate(latitude1, longitude1, latitude2, longitude2)

   @latitude1  = latitude1
   @longitude1 = longitude1
   @latitude2  = latitude2
   @longitude2 = longitude2

   @radius   = 6367.45
   @formula  = 'haversine'
   @distance = nil
end

Instance Method Details

#distanceObject

Returns the distance (in kilometers) between the two coordinates provided in the constructor.



78
79
80
81
82
83
84
# File 'lib/gis/distance.rb', line 78

def distance
   @distance =
   case @formula.to_s.downcase
      when 'haversine'
         haversine_formula
   end
end

#formulaObject

Returns the formula used to calculate the distance. The default formula is ‘haversine’. – See en.wikipedia.org/wiki/Haversine_formula for details.



57
58
59
# File 'lib/gis/distance.rb', line 57

def formula
   @formula
end

#formula=(formula) ⇒ Object

Sets the formula to be used internally for calculating the distance. The default is ‘haversine’.

If an unsupported formula is provided a GIS::Distance::Error is raised.



66
67
68
69
70
71
72
73
# File 'lib/gis/distance.rb', line 66

def formula=(formula)
   case formula.to_s.downcase
      when 'haversine'
         @formula = 'haversine'
   else
      raise Error, "Formula '#{formula}' not supported"
   end
end

#radiusObject

Returns the radius of the Earth in kilometers. The default is 6367.45.



31
32
33
# File 'lib/gis/distance.rb', line 31

def radius
   @radius
end

#radius=(kms) ⇒ Object

Sets the radius of the Earth in kilometers. This is variable because the Earth is not perfectly spherical, and you may wish to adjust it.

However, the possible range of values is limited from 6357.0 to 6378.0. If a value outside of this range is provided a GIS::Distance::Error is raised.

The default value is 6367.45.

See en.wikipedia.org/wiki/Earth_radius for more information.



46
47
48
49
50
51
# File 'lib/gis/distance.rb', line 46

def radius=(kms)
   if kms < 6357.0 || kms > 6378.0
      raise Error, "Proposed radius '#{kms}' is out of range" 
   end
   @radius = kms
end