Skip to content

Instantly share code, notes, and snippets.

@tjukanovt
Last active July 7, 2021 17:17
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save tjukanovt/9e54724221e888c2e4ac31f0bd565c91 to your computer and use it in GitHub Desktop.
Save tjukanovt/9e54724221e888c2e4ac31f0bd565c91 to your computer and use it in GitHub Desktop.
Two Python scripts that can be used to create animated route maps to multiple locations
import pandas as pd
import urllib.request
# path to your csv file with the endpoint coordinates
coordinates = pd.read_csv('swe_points.csv')
# graphhopper API call building blocks. Check Graphhopper documentation how to modify these.
urlStart = 'http://localhost:8989/route?'
point = 'point='
urlEnd = '&type=gpx&instructions=false&vehicle=car'
separator = '%2C'
# The starting point for each query (lat, lon). Use e.g. QGIS to change these.
startY = '59.3250'
startX = '18.0691'
# Make the API calls for each row in you CSV file and save the results to individual .gpx files.
for index, row in coordinates.iterrows():
req = urlStart + point + startY + separator + startX + '&' + point + str(row['Y']) + separator + str(row['X']) + urlEnd
try:
resp = urllib.request.urlopen(req)
gpxData = str(resp.read(),'utf-8')
fileName = 'sweden_' + str(index)
saveFile = open('gpx_files/{0}.gpx'.format(fileName), 'w')
print('processed index ' + str(index))
saveFile.write(gpxData)
saveFile.close()
except:
print('bad request on index ' + str(index))
pass
import gpxpy
import csv
import os
import re
#create csv file called merged.csv to working directory and give column names x, y & t
with open(r'sweden.csv', 'a') as f:
writer = csv.writer(f, quoting=csv.QUOTE_NONE, escapechar=' ', lineterminator='\n')
writer.writerow('yxt')
#create a folder for your files manually
for file in os.listdir('sweden'):
filePath = 'sweden/' + file
print(filePath)
gpx_file = open(filePath, 'r')
gpx = gpxpy.parse(gpx_file)
count = 0
#iterate through rows and append each gpx row to merged csv
for track in gpx.tracks:
for segment in track.segments:
for point in segment.points:
fields=['{0},{1},{2}'.format(point.latitude, point.longitude, point.time)]
#Here double whitespace is removed so QGIS accepts the time format
re.sub(' +',' ',fields[0])
#Graphhopper creates quite a lot of GPX points and for this purpose every second is enough.
count += 1
if count % 2 == 0:
with open(r'merged.csv', 'a') as f:
writer = csv.writer(f, quoting=csv.QUOTE_NONE, escapechar=' ', lineterminator='\n')
writer.writerow(fields)
@vaduraes
Copy link

vaduraes commented Jul 7, 2021

Can u share an example of a swe_points.csv file?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment