Class: GPXReader::Segment

Inherits:
Object
  • Object
show all
Defined in:
lib/gpx_reader/segment.rb

Constant Summary collapse

RADIUS =

caluclate the distance between 2 points en.wikipedia.org/wiki/Haversine_formula www.movable-type.co.uk/scripts/latlong.html the “Earth radius” R varies from 6356.752 km at the poles to 6378.137 km we calculate with the average radius (in km)

6371

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(segment) ⇒ Segment

Returns a new instance of Segment.



27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/gpx_reader/segment.rb', line 27

def initialize(segment)
  @distance = 0
  @points = []
  previous_pt = nil
  segment.css("trkpt").each do |pt|
    point = Point.new(pt)
    @points << point
    # calculate distance
    @distance += haversine_distance(previous_pt, point) unless previous_pt.nil?
    previous_pt = point
    # puts @points.size if @points.size.modulo(100).zero?
  end
end

Instance Attribute Details

#distanceObject

Returns the value of attribute distance.



25
26
27
# File 'lib/gpx_reader/segment.rb', line 25

def distance
  @distance
end

#pointsObject

Returns the value of attribute points.



25
26
27
# File 'lib/gpx_reader/segment.rb', line 25

def points
  @points
end

Instance Method Details

#haversine_distance(pt1, pt2) ⇒ Object

Calculate the Haversine distance between two points



48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/gpx_reader/segment.rb', line 48

def haversine_distance(pt1, pt2)
  # lat/lon are in degrees, need to convert in radiant
  # formula ==> Degrees * PI / 180
  d_lat = (pt2.lat - pt1.lat) * Math::PI / 180
  d_lon = (pt2.lon - pt1.lon) * Math::PI / 180
  lat1_r = pt1.lat * Math::PI / 180
  lat2_r = pt2.lat * Math::PI / 180
  a = Math.sin(d_lat/2) * Math.sin(d_lat/2) + Math.cos(lat1_r) * Math.cos(lat2_r) * Math.sin(d_lon/2) * Math.sin(d_lon/2)
  c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a))
  d = RADIUS * c
  return d
end