Use the WMATA api to get station locations for each line

LineCode string
Two-letter line code abbreviation:

  • RD - Red
  • YL - Yellow
  • GR - Green
  • BL - Blue
  • OR - Orange
  • SV - Silver

In [1]:
import http.client, urllib.request, urllib.parse, urllib.error, base64
import urllib
import json
import pickle

Make a function for importing the station info for each line


In [2]:
def metro_line_import(line):
    """Import station data from WMATA API and format it as a dictionary with staion name as the key and the
    [latitude, longitude] as the values"""
    headers = {
    # Request headers
    'api_key': '7f97903f83b24fcaa6dcc929bdb73437',
    }

    params = urllib.parse.urlencode({
        # Request parameters
        'LineCode': line,
    })

    try:
        conn = http.client.HTTPSConnection('api.wmata.com')
        conn.request("GET", "/Rail.svc/json/jStations?%s" % params, "{body}", headers)
        response = conn.getresponse()
        data = response.read()
        #print(data)
        conn.close()
        data_js = json.loads(data)
        line_dic = dict()
        for ii in range(len(data_js['Stations'])):
            line_dic[data_js['Stations'][ii]['Name']] = [data_js['Stations'][ii]['Lat'], data_js['Stations'][ii]['Lon']]
        #print(line_dic)
    except Exception as e:
        print("[Errno {0}] {1}".format(e.errno, e.strerror))
    return line_dic

Import the data for each line


In [3]:
lines = ['RD', 'YL', 'GR','BL', 'OR', 'SV']
line_stations = []
for ii in range(len(lines)):
    line_stations.append(metro_line_import(lines[ii]))

Turn list of dict's into dic with line (key) and stations (value)


In [4]:
station_data = dict()
for ii in range(len(lines)):
    station_data[lines[ii]] = line_stations[ii]

Use Pickel to save the dictionary of lines with the station locations


In [5]:
pickle.dump( station_data, open( "station_data.p", "wb" ) )

In [6]:
station_data['RD']['Silver Spring']


Out[6]:
[38.993841, -77.031321]

In [ ]: