Class: TspRunner::Location

Inherits:
Object
  • Object
show all
Defined in:
lib/tsp_runner/location.rb

Constant Summary collapse

RADIANS_PER_DEGREE =
Math::PI / 180
EARTH_RADIUS =

in meters

6371 * 1000

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, lat, lon) ⇒ Location

Returns a new instance of Location.

Parameters:

  • name (String)

    the name of the location

  • lat (Fixnum)

    the latitude

  • lon (Fixnum)

    the longitude



11
12
13
14
15
16
17
18
19
20
21
# File 'lib/tsp_runner/location.rb', line 11

def initialize(name, lat, lon)
  unless lat.in?(-90..90)
    raise ArgumentError, 'Latitudue should be between -90 and 90'
  end

  unless lon.in?(-180..180)
    raise ArgumentError, 'Longitudue should be between -180 and 180'
  end

  @name, @lat, @lon = name, lat, lon
end

Instance Attribute Details

#latObject (readonly)

Returns the value of attribute lat.



6
7
8
# File 'lib/tsp_runner/location.rb', line 6

def lat
  @lat
end

#lonObject (readonly)

Returns the value of attribute lon.



6
7
8
# File 'lib/tsp_runner/location.rb', line 6

def lon
  @lon
end

#nameObject (readonly)

Returns the value of attribute name.



6
7
8
# File 'lib/tsp_runner/location.rb', line 6

def name
  @name
end

Instance Method Details

#distance_from(location) ⇒ Fixnum

Returns:

  • (Fixnum)

    the Haversine distance of the location (from self) as measured in meters



38
39
40
41
42
43
44
45
46
47
# File 'lib/tsp_runner/location.rb', line 38

def distance_from(location)
  delta_lat = location.lat_rad - lat_rad
  delta_lon = location.lon_rad - lon_rad

  a = Math.sin(delta_lat / 2) ** 2 + Math.cos(lat_rad) *
      Math.cos(location.lat_rad) * Math.sin(delta_lon / 2) ** 2
  c = 2 * Math::atan2(Math::sqrt(a), Math::sqrt(1 - a))

  EARTH_RADIUS * c
end

#lat_radFixnum

Returns the latitude in radians.

Returns:

  • (Fixnum)

    the latitude in radians



24
25
26
# File 'lib/tsp_runner/location.rb', line 24

def lat_rad
  lat * RADIANS_PER_DEGREE
end

#lon_radFixnum

Returns the longitude in radians.

Returns:

  • (Fixnum)

    the longitude in radians



29
30
31
# File 'lib/tsp_runner/location.rb', line 29

def lon_rad
  lon * RADIANS_PER_DEGREE
end