Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
# -*- coding: utf-8 -*-
"""
Example on how to add elevations to existing GPX file
"""
import gpxpy as mod_gpxpy
import srtm as mod_srtm
gpx_contents = """test2714.02652.02414.02679.02710.02145.02004.01782.01592.02714.02522.02421.02099.01689.02080.02279.02343.01973.0"""
gpx = mod_gpxpy.parse(gpx_contents)
geo_elevation_data = mod_srtm.get_data()
for segment_no, segment in enumerate(gpx.tracks[0].segments):
for point in segment.points:
calculated = geo_elevation_data.get_elevation(point.latitude, point.longitude)
print 'segment #%s (%13s, %13s) -> gpx:%10s calculated:%10s' % (segment_no, point.latitude, point.longitude, point.elevation, calculated)
def read_gpx_file(self, filename):
try:
with open(filename, "r") as f:
prev_point = None
head, tail = os.path.split(filename)
code_route = tail.replace(".gpx", "")
try:
gpx = gpxpy.parse(f)
for point in gpx.walk(only_points=True):
speed = point.speed_between(prev_point)
if speed is None:
speed = 0
time_difference = point.time_difference(prev_point)
if time_difference is None:
time_difference = 0
distance = point.distance_3d(prev_point)
if not distance:
distance = point.distance_2d(prev_point)
if distance is None:
distance = 0
self.points_list.append([code_route, point.latitude, point.longitude, point.elevation,
def get_lat_lon_time(gpx_file, gpx_time='utc'):
'''
Read location and time stamps from a track in a GPX file.
Returns a list of tuples (time, lat, lon, elevation).
GPX stores time in UTC, assume your camera used the local
timezone and convert accordingly.
'''
with open(gpx_file, 'r') as f:
gpx = gpxpy.parse(f)
points = []
for track in gpx.tracks:
for segment in track.segments:
for point in segment.points:
ptime = utc_to_localtime(point.time) if gpx_time=='utc' else point.time
points.append( (ptime, point.latitude, point.longitude, point.elevation) )
# sort by time just in case
points.sort()
return points
@staticmethod
def from_gpx(file_path):
""" Creates a Track from a GPX file.
No preprocessing is done.
Arguments:
file_path (str): file path and name to the GPX file
Return:
:obj:`list` of :obj:`Track`
"""
gpx = gpxpy.parse(open(file_path, 'r'))
file_name = basename(file_path)
tracks = []
for i, track in enumerate(gpx.tracks):
segments = []
for segment in track.segments:
segments.append(Segment.from_gpx(segment))
if len(gpx.tracks) > 1:
name = file_name + "_" + str(i)
else:
name = file_name
tracks.append(Track(name, segments))
return tracks
Args:
file_name: GPX file to be loaded .
Raises:
TrackLoadError: An error occurred while parsing the GPX file (empty or bad format).
PermissionError: An error occurred while opening the GPX file.
"""
try:
self.file_names = [os.path.basename(file_name)]
# Handle empty gpx files
# (for example, treadmill runs pulled via garmin-connect-export)
if os.path.getsize(file_name) == 0:
raise TrackLoadError("Empty GPX file")
with open(file_name, "r") as file:
self._load_gpx_data(mod_gpxpy.parse(file))
except TrackLoadError as e:
raise e
except mod_gpxpy.gpx.GPXXMLSyntaxException as e:
raise TrackLoadError("Failed to parse GPX.") from e
except PermissionError as e:
raise TrackLoadError("Cannot load GPX (bad permissions)") from e
except Exception as e:
raise TrackLoadError("Something went wrong when loading GPX.") from e
def open_gpx_file(gpx_file):
gpx_file = open(gpx_file, 'r')
gpx = gpxpy.parse(gpx_file)
if len(gpx.tracks) == 0:
return None
return gpx
def plot_trail(lat, lon, gpx_file, my_curr_location):
pts = []
gpx_file = open(params['trails'] + "/" + gpx_file)
gpx = gpxpy.parse(gpx_file)
for track in gpx.tracks:
for segment in track.segments:
for point in segment.points:
pts.append([point.latitude, point.longitude])
clean_dir()
fout = "static/out-%s.png" % uuid.uuid4()
map = OnlyOne().map
zfile,scale = params['mapzip'][map]
plot_map.plot2(pts, fout, zfile=zfile, scale=scale, map_retrieval_on=(lat,lon), my_curr_location=my_curr_location, pixel=True)
return fout
def read_file(self, path):
with open(path) as gpx_file:
gpx = gpxpy.parse(gpx_file)
for track in gpx.tracks:
for segment in track.segments:
for point in segment.points:
yield point
for route in gpx.routes:
for point in route.points:
yield point
for point in gpx.waypoints:
yield point
def get_lat_lon_time_from_gpx(gpx_file, local_time=True):
'''
Read location and time stamps from a track in a GPX file.
Returns a list of tuples (time, lat, lon).
GPX stores time in UTC, by default we assume your camera used the local time
and convert accordingly.
'''
with open(gpx_file, 'r') as f:
gpx = gpxpy.parse(f)
points = []
if len(gpx.tracks) > 0:
for track in gpx.tracks:
for segment in track.segments:
for point in segment.points:
t = utc_to_localtime(point.time) if local_time else point.time
points.append((t, point.latitude, point.longitude, point.elevation))
if len(gpx.waypoints) > 0:
for point in gpx.waypoints:
t = utc_to_localtime(point.time) if local_time else point.time
points.append((t, point.latitude, point.longitude, point.elevation))
# sort by time just in case
points.sort()