Search code examples
rubyorientationcompass-geolocationbearing

Convert orientation (N, S, SE, SSE etc) to bearing angle


Is there a functionality in ruby or a gem to convert a string with an orientation (examples in title) to a bearing in degrees, with the bearing defined as follows?

A numerical value representing the direction in degrees, with true north at 0° and progressing clockwise.


Solution

  • This works for the 8 main cardinal directions:

    def cardinal_direction_degrees(s)
      h = {n: 0, ne: 45, e: 90, se: 135, s: 180, sw: 225, w: 270, nw: 315}
      h[s.to_s.downcase.to_sym]
    end
    
    puts cardinal_direction_degrees('N') #=> 0
    puts cardinal_direction_degrees('SW') #=> 225
    

    You can easily add the remaining directions by adding more elements to the hash.