Class: Iata::Coordinates

Inherits:
Object
  • Object
show all
Defined in:
lib/iata/coordinates.rb

Overview

Geographic coordinates (WGS-84) for an IATA airport entry.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(latitude: nil, longitude: nil) ⇒ Coordinates

Returns a new instance of Coordinates.



8
9
10
11
# File 'lib/iata/coordinates.rb', line 8

def initialize(latitude: nil, longitude: nil)
  @latitude = latitude&.to_f
  @longitude = longitude&.to_f
end

Instance Attribute Details

#latitudeObject (readonly)

Returns the value of attribute latitude.



6
7
8
# File 'lib/iata/coordinates.rb', line 6

def latitude
  @latitude
end

#longitudeObject (readonly)

Returns the value of attribute longitude.



6
7
8
# File 'lib/iata/coordinates.rb', line 6

def longitude
  @longitude
end

Instance Method Details

#==(other) ⇒ Object



17
18
19
20
21
# File 'lib/iata/coordinates.rb', line 17

def ==(other)
  other.is_a?(Coordinates) &&
    latitude == other.latitude &&
    longitude == other.longitude
end

#distance_to(other) ⇒ Object

Great-circle distance in kilometres to another Coordinates, using the haversine formula. Returns nil if either side lacks coordinates.



31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/iata/coordinates.rb', line 31

def distance_to(other)
  return nil if latitude.nil? || longitude.nil? ||
                other.latitude.nil? || other.longitude.nil?

  earth_radius_km = 6371.0
  d_lat = (other.latitude - latitude) * (Math::PI / 180)
  d_lon = (other.longitude - longitude) * (Math::PI / 180)
  a = (Math.sin(d_lat / 2)**2) +
      (Math.cos(latitude * (Math::PI / 180)) *
       Math.cos(other.latitude * (Math::PI / 180)) *
       (Math.sin(d_lon / 2)**2))
  2 * earth_radius_km * Math.asin(Math.sqrt(a))
end

#to_aObject



13
14
15
# File 'lib/iata/coordinates.rb', line 13

def to_a
  [latitude, longitude].compact
end

#to_sObject



23
24
25
26
27
# File 'lib/iata/coordinates.rb', line 23

def to_s
  return '' if latitude.nil? || longitude.nil?

  format('%<lat>.4f %<lon>.4f', lat: latitude, lon: longitude)
end