apis




Pay Notebook Creator: Salah Ahmed0
Set Container: Numerical CPU with TINY Memory for 10 Minutes 0
Total0

Distance Calculator

use googles distance matrix api to find travel times for all destinations from origins

I built this app to choose hotels when traveling to cities for conferences or weddings

In [1]:
# Crosscompute

origins_text_path = 'origin.txt'
destinations_text_path = 'dest.txt'
mode_select = '''
       driving
       
       driving
       walking
       cycling
       '''
target_folder = 'results'
In [2]:
def load_unique_lines(source_path):
    if not source_path:
        return []
    with open(source_path, 'r') as f:
        lines = set((x.strip('\n ,;') for x in f))
    return sorted(filter(lambda x: x, lines))
In [3]:
from os.path import join
import geopy
import numpy as np
import requests
from pandas import DataFrame
In [4]:
from itertools import takewhile
origins = load_unique_lines(origins_text_path)
destinations = load_unique_lines(destinations_text_path)
mode = next(takewhile(lambda x: x.strip(), mode_select.strip().splitlines())).strip()
In [5]:
# Use google's distancematrix api
url = "https://maps.googleapis.com/maps/api/distancematrix/json?"
url_params = {"origins": "|".join(origins),
              "mode": mode,
              "destinations": "|".join(destinations),
              "language": "en-EN",
              "units": "imperial",
              "key": 'AIzaSyBhNXrJJKvAj6-h5ceUe769JM-u4olg6Jo'}
response = requests.get(url, params=url_params).json()
if response['status'] != 'OK':
    raise Exception('api error :/, check addresses')
In [6]:
origins, destinations = (response['origin_addresses'],
                         response['destination_addresses'])
In [7]:
d = [[i['duration']['value'] for i in x['elements']] for x in response['rows']]
d
Out[7]:
[[1267, 1642, 2072], [1111, 1391, 1821], [747, 385, 1622]]
In [8]:
df = DataFrame(d, columns=destinations, index=origins)
df.index.name = 'origins'
df['total'] = df.sum(axis=1)
df = df.sort_values(by='total')
df
Out[8]:
<style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style>
7216 W 87th St, Bridgeview, IL 60455, USA Chicago Midway International Airport (MDW), 5700 S Cicero Ave, Chicago, IL 60638, USA 2301 S King Dr, Chicago, IL 60616, USA total
origins
7353 S Cicero Ave, Chicago, IL 60629, USA 747 385 1622 2754
855 79th St, Willowbrook, IL 60527, USA 1111 1391 1821 4323
669 Pasquinelli Dr, Westmont, IL 60559, USA 1267 1642 2072 4981
In [9]:
results_path = join(target_folder, 'results.csv')
df.to_csv(results_path)
print("results_table_path = {0}".format(results_path))
results_table_path = results/results.csv
In [10]:
google_geo = geopy.GoogleV3()
minimum_pixel_size, max_pixel_size = 10, 50
origins_color = 'red'
destinations_color = 'blue'
destinations_pixel_size = 10
In [11]:
sizes = np.linspace(minimum_pixel_size,
                    max_pixel_size,
                    len(df.index))[::-1]
sizes = np.append(sizes, np.full(len(destinations), destinations_pixel_size))
sizes
Out[11]:
array([50., 30., 10., 10., 10., 10.])
In [12]:
geotable = DataFrame(index=np.append(df.index, (destinations)))
geotable.index.name = 'address'
geotable['radius_in_pixels'] = sizes
geotable['FillColor'] = [origins_color] * len(origins) + [destinations_color] * len(destinations)
geotable.head()
Out[12]:
<style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style>
radius_in_pixels FillColor
address
7353 S Cicero Ave, Chicago, IL 60629, USA 50.0 red
855 79th St, Willowbrook, IL 60527, USA 30.0 red
669 Pasquinelli Dr, Westmont, IL 60559, USA 10.0 red
7216 W 87th St, Bridgeview, IL 60455, USA 10.0 blue
Chicago Midway International Airport (MDW), 5700 S Cicero Ave, Chicago, IL 60638, USA 10.0 blue
In [13]:
# geocode address
from geopy.geocoders.googlev3 import GeocoderQuotaExceeded
from time import sleep


def get_coordinates(x):
    for i in range(3):
        try:
            c = google_geo.geocode(x)
            return [c.latitude, c.longitude]
        except GeocoderQuotaExceeded:
            print('geocoder quota exceeded, trying again')
            sleep(3)
            continue
    else:
        print('geocoder.error = GeocoderQuotaExceeded')
        raise GeocoderQuotaExceeded

geotable['coord'] = geotable.index.map(get_coordinates)
geocoder quota exceeded, trying again
In [14]:
geotable['latitude'] = geotable['coord'].apply(lambda x: x[0])
geotable['longitude'] = geotable['coord'].apply(lambda x: x[1])
del geotable['coord']
geotable
Out[14]:
<style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style>
radius_in_pixels FillColor latitude longitude
address
7353 S Cicero Ave, Chicago, IL 60629, USA 50.0 red 41.758827 -87.741027
855 79th St, Willowbrook, IL 60527, USA 30.0 red 41.744581 -87.943383
669 Pasquinelli Dr, Westmont, IL 60559, USA 10.0 red 41.812890 -87.948664
7216 W 87th St, Bridgeview, IL 60455, USA 10.0 blue 41.733813 -87.801211
Chicago Midway International Airport (MDW), 5700 S Cicero Ave, Chicago, IL 60638, USA 10.0 blue 41.786776 -87.752188
2301 S King Dr, Chicago, IL 60616, USA 10.0 blue 41.851229 -87.617034
In [15]:
geomap_path = join(target_folder, 'geomap.csv')
geotable.to_csv(geomap_path)
print("points_geotable_path = {0}".format(geomap_path))
points_geotable_path = results/geomap.csv