Skip to content

Instantly share code, notes, and snippets.

@scascketta
Last active September 3, 2024 03:00
Show Gist options
  • Save scascketta/13208103fd6be9fb7df7 to your computer and use it in GitHub Desktop.
Save scascketta/13208103fd6be9fb7df7 to your computer and use it in GitHub Desktop.
How to use CapMetro's API to see where every vehicle is in real-time with Python

Parsing GTFS-Realtime with Python

Install dependencies

pip install gtfs-realtime-bindings requests

Code

#!/usr/bin/env python

from datetime import datetime

import requests
from google.transit import gtfs_realtime_pb2

# Live vehicle position updates for every CapMetro vehicle 24/7
CAPMETRO_URL = 'https://data.texas.gov/download/i5qp-g5fd/application/octet-stream'

res = requests.get(CAPMETRO_URL)
feed = gtfs_realtime_pb2.FeedMessage()
feed.ParseFromString(res.content)

for entity in feed.entity:
    v = entity.vehicle

    if not v.trip.route_id:
        # vehicle is not in service
        continue

    msg = 'Vehicle {id} located at ({lat},{lon}) on route {route} at {timestamp}'
    print msg.format(
        id=v.vehicle.id,
        lat=v.position.latitude,
        lon=v.position.longitude,
        route=v.trip.route_id,
        timestamp=datetime.utcfromtimestamp(int(v.timestamp))
    )

Example Output

Vehicle 2059 located at (30.2690181732,-97.7426528931) on route 486 at 2015-09-03 06:05:31
Vehicle 8910 located at (30.1877002716,-97.7631378174) on route 486 at 2015-09-03 06:03:56
Vehicle 8925 located at (30.2421226501,-97.7843856812) on route 484 at 2015-09-03 06:03:39
Vehicle 2233 located at (30.3545150757,-97.7041473389) on route 481 at 2015-09-03 06:03:56
Vehicle 8903 located at (30.2715206146,-97.7443313599) on route 481 at 2015-09-03 06:05:09
Vehicle 2206 located at (30.2705841064,-97.7136764526) on route 485 at 2015-09-03 06:04:38
Vehicle 8914 located at (30.3089466095,-97.7094345093) on route 485 at 2015-09-03 06:04:22
Vehicle 8926 located at (30.244020462,-97.7299880981) on route 20 at 2015-09-03 06:04:23
Vehicle 8918 located at (30.3164825439,-97.7321395874) on route 481 at 2015-09-03 06:04:48
Vehicle 2402 located at (30.2318382263,-97.7331848145) on route 483 at 2015-09-03 06:04:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment