#!/usr/bin/env python # coding: utf-8 # Created by: [SmirkyGraphs](https://smirkygraphs.github.io/). Code: [Github](https://github.com/SmirkyGraphs/Python-Notebooks). Source: [Dunkin](https://www.dunkindonuts.com/en/locations). #
# # Rhode Island Dunkin' Location Routes # This notebook is to get the closest path to every dunkin in the state from 3 specific locations. From the center of the state, the state airport and the state house in Providence. Through using pandas and requests to query GraphHopper Routing API from localhost and parse the gpx results using gpxpy. # # requirements: [QGIS](https://qgis.org/en/site/forusers/download.html), [GraphHopper](https://github.com/graphhopper/graphhopper) # inspiration/tutorial: [Topi Tjukanov](https://medium.com/@tjukanov/animated-routes-with-qgis-9377c1f16021) # In[1]: import pandas as pd import requests import datetime import gpxpy import glob # In[2]: df = pd.read_csv('./data/input/dunkin_locations.csv') df = df[df['state'] == 'RI'] df = df['shapePoints'].str.strip('[]') df = df.str.split(', ', expand=True) df.columns = ['Y', 'X'] dunkins = df.reset_index(drop=True) # The starting point for each query start_x = '-71.435256' start_y = '41.725856' url = 'http://localhost:8989/route?' url_end = '&type=gpx&instructions=false&vehicle=car' for i, row in dunkins.iterrows(): lookup_x = str(row['X']) lookup_y = str(row['Y']) req = url + f'point={start_y}%2C{start_x}' + '&' + f'point={lookup_y}%2C{lookup_x}' + url_end r = requests.get(req) gpx_data = (r.content).decode('utf-8') file = f'data/raw/state_airport/ri_dunkin_{i}.gpx' with open(file, 'w') as f: f.write(gpx_data) f.close() # In[3]: files = glob.glob('./data/raw/state_airport/*.gpx') tracks_frame = [] for file in files: with open(file, 'r') as f: gpx = gpxpy.parse(f) tracks = [track for track in gpx.tracks][0] segments = [segment for segment in tracks.segments][0] for point in segments.points: data = {} data['Y'] = point.latitude data['X'] = point.longitude data['T'] = point.time tracks_frame.append(data) df = pd.DataFrame(tracks_frame) # convert time df['T'] = df['T'].dt.strftime('%Y-%m-%d %H:%M:%S.%f') # save file df.to_csv('./data/clean/state_airport_merged.csv') # In[4]: gpx = gpxpy.parse(f) tracks = [track for track in gpx.tracks][0] segments = [segment for segment in tracks.segments][0] for point in segments.points: data = {} data['Y'] = point.latitude data['X'] = point.longitude data['T'] = point.time tracks_frame.append(data) df = pd.DataFrame(tracks_frame) # convert time df['T'] = df['T'].dt.strftime('%Y-%m-%d %H:%M:%S.%f') # save file df.to_csv('./data/clean/state_airport_merged.csv')