Skip to content

Instantly share code, notes, and snippets.

@AlexandraKapp
Last active November 18, 2022 16:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AlexandraKapp/932500372086a309015c7dd429e78bb9 to your computer and use it in GitHub Desktop.
Save AlexandraKapp/932500372086a309015c7dd429e78bb9 to your computer and use it in GitHub Desktop.
# snap GPS trajectories to OSM road network
# expected csv format: tid,lon,lat
# where tid is the trip id, where all coordinates of the same trip share the same id
# the order of coordinates is expected to be in correct order
# setup OSRM server: https://hub.docker.com/r/osrm/osrm-backend/
import csv
import requests
INPUT_FILE_PATH = "data/input.csv"
OUTPUT_FILE_PATH = "data/output.csv"
# read in file
with open(INPUT_FILE_PATH, "rt") as fin:
cr = csv.reader(fin)
filecontents = [line for line in cr]
tids = [line[0] for line in filecontents]
lons = [line[1] for line in filecontents]
lats = [line[2] for line in filecontents]
lon_lats = [",".join((lon, lat)) for lon, lat in list(zip(lons, lats))]
with open(OUTPUT_FILE_PATH, 'w') as csvfile:
write = csv.writer(csvfile)
write.writerow(["tid", "lon", "lat"])
for tid in set(tids):
indices_tid = [i for i in range(len(tids)) if tids[i] == tid]
coords_query_format = ";".join(lon_lats[min(indices_tid):max(indices_tid)])
# query osrm
query_string = f"http://127.0.0.1:5000/match/v1/driving/{coords_query_format}?steps=true&geometries=geojson&overview=simplified&annotations=false"
request = requests.get(query_string)
if request == 400:
coordinates = request.json()['matchings'][0]['geometry']['coordinates']
# write to file
for coord_pair in coordinates:
write.writerow([tid, coord_pair[0], coord_pair[1]])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment