Skip to content

Instantly share code, notes, and snippets.

@bverhoeve
Created November 11, 2020 13:09
Show Gist options
  • Save bverhoeve/01390d7311af0b267f763e11604c92f2 to your computer and use it in GitHub Desktop.
Save bverhoeve/01390d7311af0b267f763e11604c92f2 to your computer and use it in GitHub Desktop.
Parse GPX files to Xcode format
import logging
import os
from typing import List
import gpxpy
# Use
# Put the GPX files you want to parse in a folder 'gpx_files' next to this file
# Execute the file in a terminal: 'python3 parse_gpx.py'
# The output GPX files will be in a folder called 'parsed_files'
# Note the files to be parsed follow the format as generated by the myTracks application (https://apps.apple.com/us/app/mytracks-the-gps-logger/id358697908)
GPX_FILE_EXT = '.gpx'
INPUT_DATA = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'gpx_files')
OUTPUT_DATA = 'parsed_files'
def discover_files(dir: str) -> List:
discovered_files = []
for root, dirs, files in os.walk(dir):
discovered_files += [os.path.join(root, file) for file in files if file.endswith('.gpx')]
return discovered_files
def read_track(gpx_file_path: str) -> gpxpy.gpx.GPXTrack:
with open(gpx_file_path, 'r') as gpx_file:
gpx = gpxpy.parse(gpx_file)
# Our gpx files only contain 1 track
return gpx.tracks[0]
def parse_track_to_waypoints(track: gpxpy.gpx.GPXTrack):
# Our tracks only contain 1 segment with multiple points
gpx = gpxpy.gpx.GPX()
gpx.name = track.name
for point in track.segments[0].points:
gpx.waypoints.append(gpxpy.gpx.GPXWaypoint(
latitude = point.latitude,
longitude = point.longitude,
elevation = point.elevation,
time = point.time,
))
return gpx
def write_gpx_file(gpx: gpxpy.gpx.GPX) -> str:
# Check if output directory exists or not
output_dir: str = os.path.join(os.getcwd(), OUTPUT_DATA)
if not os.path.exists(output_dir):
os.makedirs(output_dir)
xml_string: str = gpx.to_xml()
gpx_file_path = os.path.join(output_dir, f'ios_{gpx.name}{GPX_FILE_EXT}')
with open(gpx_file_path, 'w') as file:
file.write(xml_string)
return gpx_file_path
def main():
logging.info('Discovering files...')
files = discover_files(INPUT_DATA)
logging.info(f'Discovered {len(files)} files')
logging.info('Parsing files...')
for file in files:
logging.info(f'Reading file {file}')
track: gpxpy.gpx.GPXTrack = read_track(file)
logging.info(f'Parsing track {track.name}')
gpx_wpts = parse_track_to_waypoints(track)
logging.debug(f'Writing parsed GPX file')
written_file: str = write_gpx_file(gpx_wpts)
logging.debug(f'Written file {written_file}')
logging.info('Done!')
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment