Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Combine Halfmile GPX segments into one or a few big GPX files
#! /usr/bin/env python3
Program: Combine Halfmile GPX tracks into a single GPX track
Author: Kyle Barron
import io
import requests
import gpxpy
import gpxpy.gpx
from zipfile import ZipFile
def main():
for state in ['ca1', 'ca2', 'or', 'wa']:
gpxs = download_gpx_tracks(state[:2])
tracks, waypoints = split_into_tracks_and_waypoints(gpxs)
split = int(state[2]) if state.startswith('ca') else None
tracks = combine(sort_gpxs(tracks), split)
waypoints = combine(sort_gpxs(waypoints), split)
with open(f'{state}_pct_tracks.gpx', 'w') as f:
with open(f'{state}_pct_waypoints.gpx', 'w') as f:
def download_gpx_tracks(state):
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}
unzipped_content = {}
url = ''
url += f'/{state}'
r = requests.get(url, headers=headers)
content = io.BytesIO(r.content)
with ZipFile(content) as zf:
for name in zf.namelist():
if not name.startswith(state):
if not name.endswith('.gpx'):
unzipped_content[name] ='utf-8')
return unzipped_content
def split_into_tracks_and_waypoints(gpxs):
tracks = {}
waypoints = {}
for name, data in gpxs.items():
if name.endswith('tracks.gpx'):
tracks[name] = data
elif name.endswith('waypoints.gpx'):
waypoints[name] = data
raise Exception()
return tracks, waypoints
def sort_gpxs(gpx):
return dict(sorted(gpx.items()))
def combine(gpx, split=None):
new_gpx = gpxpy.gpx.GPX()
if split is not None:
if split == 1:
gpx = dict(list(gpx.items())[:len(gpx) // 2])
elif split == 2:
gpx = dict(list(gpx.items())[len(gpx) // 2:])
raise Exception('split must be 1, 2, or None')
for name, g in gpx.items():
g = gpxpy.parse(g)
for track in g.tracks:
for waypoint in g.waypoints:
for route in g.routes:
return new_gpx
if __name__ == '__main__':
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.