Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!
Guest

getpathdata.py - SF Muni Google Map

By: asweigart on Feb 10th, 2014  |  syntax: Python  |  size: 1.37 KB  |  views: 77  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. import pprint, requests, routedata # routedata has the allRoutes variable with the route name info
  2. import xml.etree.ElementTree as ET
  3.  
  4. allRoutesPathData = {} # this will be the big dictionary we store all data in
  5. for route in routedata.allRoutes: # loop through all the routes
  6.     allRoutesPathData[route] = [] # this will be a list of lists of {'lon':XXX, 'lat':XXX} dictonaries
  7.  
  8.     req = requests.get('http://webservices.nextbus.com/service/publicXMLFeed?command=routeConfig&a=sf-muni&r=%s' % (route))
  9.     if req.status_code != 200:
  10.         raise Exception('Could not download route data for %s' % (route))
  11.  
  12.     # load the downloaded XML text into an XML object we can navigate
  13.     root = ET.fromstring(req.text)
  14.     for child in root[0]: # iterate over all the elements in the <route> element
  15.         if child.tag != 'path':
  16.             continue # skip the non-<path> elements
  17.  
  18.         pathElement = []
  19.         for point in child: # child is a <path> element, point is a <point> element in the path
  20.             pathElement.append({'lon': point.attrib['lon'], 'lat': point.attrib['lat']}) # append this point to the path
  21.         allRoutesPathData[route].append(pathElement) # append the path to the main dictionary
  22.  
  23. # output all the data to a file named munipaths.py:
  24. fo = open('munipaths.py', 'w')
  25. fo.write('munipaths = ' + pprint.pformat(allRoutesPathData))
  26. fo.close()