Skip to content

Instantly share code, notes, and snippets.

@alexsoble
Forked from nrrb/station_distances.py
Last active December 31, 2015 02:19
Show Gist options
  • Save alexsoble/7920166 to your computer and use it in GitHub Desktop.
Save alexsoble/7920166 to your computer and use it in GitHub Desktop.
from time import sleep
import json
import csv
import re
import requests
from omgsecrets import SMART_CHICAGO_URL
from omgsecrets import SMART_CHICAGO_KEY
def distance(station1, station2):
origins = str(station1["latitude"]) + "," + str(station1["longitude"])
destinations = str(station2["latitude"]) + "," + str(station2["longitude"])
r = requests.get(
SMART_CHICAGO_URL + "?origins=" + origins + "&destinations=" + destinations + "&sensor=false" + "&mode=bicycling&units=imperial&key=" + SMART_CHICAGO_KEY
)
if r.status_code != 200:
# We didn't get a response from Google
return -1
result = json.loads(r.content)
try:
distance = result["rows"][0]["elements"][0]["distance"]["text"]
except IndexError, KeyError:
# We didn't get the response we expected from Google
return -1
return distance
if __name__ == "__main__":
r = requests.get(DIVVY_STATIONS_URL)
if r.status_code != 200:
print("ERROR: Couldn't get the station list from Divvy Bikes.")
exit(1)
station_data = json.loads(r.content)
stations = station_data['stationBeanList']
f = open('station_distances.csv', 'wb')
csvwriter = csv.writer(f)
csvwriter.writerow(['stationName1', 'stationName2', 'distance (miles)'])
for station1 in stations:
for station2 in stations:
# Skip this iteration if the stations are the same
if station1['stationName'] == station2['stationName']:
continue
# If the pair (station1, station2) has already been checked,
# we want to skip checking (station2, station1). We need to
# split the input in exactly half, so any given pair is only
# checked once. One way to do this is by the natural string
# ordering. In Python, 'a' < 'b' because 'a' comes before
# 'b' alphabetically. For any two strings A and B, it's true
# that either A < B or A > B (unless A is B, but we already
# check for that). If we check for ordering, we can quickly
# split our input space in half.
if station1['stationName'] > station2['stationName']:
continue
d = distance(station1, station2)
csvwriter.writerow([station1['stationName'], station2['stationName'], d])
print('Distance between {station1} and {station2} is {d}.'.format(
station1=station1['stationName'], station2=station2['stationName'], d=d
))
# Let's be nice to Google and wait a tiny bit in between requests
sleep(0.1)
f.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment