Skip to content

Instantly share code, notes, and snippets.

@titanous
Created January 2, 2011 19:45
Show Gist options
  • Save titanous/762761 to your computer and use it in GitHub Desktop.
Save titanous/762761 to your computer and use it in GitHub Desktop.
OC Transpo GPS API access in Ruby
require 'open-uri'
require 'nokogiri'
require 'active_support/time'
module OCTranspo
class GPSData
API_URL = 'http://octranspo.opendataottawa.ca'
API_KEY = 'YOUR API KEY HERE'
def initialize(stop)
@stop = stop
end
def trips(count = 3)
url = "#{API_URL}/stop/#{@stop}/trips?count=#{count}&key=#{API_KEY}"
doc = Nokogiri::XML(open(url))
trips = {}
doc.xpath('//xmlns:StopNextTripData', 'xmlns' => 'http://tempuri.org/').each do |trip|
route = get_el(trip, 'ROUTE_NO').to_i
direction = get_el(trip, 'DIRECTION')
trips[route] ||= {}
trips[route][direction[0,1]] ||= []
trip_details = {
:route => route,
:description => get_el(trip, 'ROUTE_DESCRIPTION').gsub(/\s?[\/\\-]+\s?/, '/'),
:direction => direction,
:live => get_el(trip, 'GPS_AVAILABLE') == 'true',
:last_trip => get_el(trip, 'LAST_TRIP') == 'true'
}
scheduled_seconds = get_el(trip, 'SCHEDULED_SECONDS').to_i
trip_details[:scheduled_arrival] = seconds_to_time(scheduled_seconds)
if trip_details[:live]
trip_details.merge!({
:latitude => get_el(trip, 'LATITUDE').to_f,
:longitude => get_el(trip, 'LONGITUDE').to_f,
:estimated_arrival => seconds_to_time(scheduled_seconds + get_el(trip, 'ADHERENCE_SECONDS').to_i)
})
end
trips[route][direction[0,1]] << trip_details
end
trips
end
def route_trips(route, count = 3)
trips(count)[route.to_i]
end
def next_route_trip(route, direction = nil)
trips = route_trips(route, 1)
flattened_trips = direction ? trips[direction.upcase] : trips.to_a.flatten.select { |e| e.is_a?(Hash) }
flattened_trips.sort { |a,b| (a[:estimated_arrival] || a[:scheduled_arrival]) <=>
(b[:estimated_arrival] || b[:scheduled_arrival]) }.first
end
private
def seconds_to_time(seconds)
ActiveSupport::TimeZone['America/Toronto'].now.midnight + (seconds.to_i % 86400)
end
def get_el(node, el)
node.at_xpath('xmlns:' + el, 'xmlns' => 'http://tempuri.org/').content
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment