0
# GPX Track Processing
1
2
Integration with GPX files to add elevation data to GPS tracks, with options for smoothing, interpolation, and batch processing of multiple tracks.
3
4
## Capabilities
5
6
### Adding Elevations to GPX Tracks
7
8
Add elevation data to GPX track points with configurable options for handling existing data and applying smoothing algorithms.
9
10
```python { .api }
11
class GeoElevationData:
12
def add_elevations(
13
self,
14
gpx,
15
only_missing: bool = False,
16
smooth: bool = False,
17
gpx_smooth_no: int = 0
18
) -> None: ...
19
```
20
21
**Parameters:**
22
- `gpx`: GPX object (from gpxpy library) containing tracks to process
23
- `only_missing` (bool): Only add elevations to points that don't already have elevation data. Default: False
24
- `smooth` (bool): Apply interpolated elevation sampling for smoother elevation profiles. Default: False
25
- `gpx_smooth_no` (int): Number of smoothing passes to apply. Default: 0 (no additional smoothing)
26
27
**Returns:** None (modifies the GPX object in-place)
28
29
**Usage Example:**
30
```python
31
import srtm
32
import gpxpy
33
34
# Load GPX file
35
with open('track.gpx', 'r') as gpx_file:
36
gpx = gpxpy.parse(gpx_file.read())
37
38
# Create elevation data object
39
elevation_data = srtm.get_data()
40
41
# Add elevations to all track points
42
elevation_data.add_elevations(gpx)
43
44
# Save modified GPX
45
with open('track_with_elevations.gpx', 'w') as output_file:
46
output_file.write(gpx.to_xml())
47
48
print(f"Processed {gpx.get_track_points_no()} track points")
49
```
50
51
### Selective Elevation Processing
52
53
Add elevations only to track points that are missing elevation data, preserving existing elevation information.
54
55
**Usage Example:**
56
```python
57
import srtm
58
import gpxpy
59
60
# Load GPX that may already have some elevation data
61
with open('partial_track.gpx', 'r') as gpx_file:
62
gpx = gpxpy.parse(gpx_file.read())
63
64
elevation_data = srtm.get_data()
65
66
# Only fill missing elevations, preserve existing data
67
elevation_data.add_elevations(gpx, only_missing=True)
68
69
# Count points with elevation data
70
points_with_elevation = sum(
71
1 for track in gpx.tracks
72
for segment in track.segments
73
for point in segment.points
74
if point.elevation is not None
75
)
76
print(f"Points with elevation data: {points_with_elevation}")
77
```
78
79
### Smooth Elevation Profiles
80
81
Apply interpolation and smoothing to create more natural elevation profiles, reducing noise from discrete SRTM data points.
82
83
**Usage Example:**
84
```python
85
import srtm
86
import gpxpy
87
88
# Load GPX file
89
with open('noisy_track.gpx', 'r') as gpx_file:
90
gpx = gpxpy.parse(gpx_file.read())
91
92
elevation_data = srtm.get_data()
93
94
# Add smoothed elevations with multiple smoothing passes
95
elevation_data.add_elevations(
96
gpx,
97
smooth=True, # Enable interpolated sampling
98
gpx_smooth_no=2 # Apply 2 additional smoothing passes
99
)
100
101
# Calculate elevation statistics
102
elevations = [
103
point.elevation for track in gpx.tracks
104
for segment in track.segments
105
for point in segment.points
106
if point.elevation is not None
107
]
108
109
if elevations:
110
print(f"Elevation range: {min(elevations):.1f}m to {max(elevations):.1f}m")
111
print(f"Average elevation: {sum(elevations)/len(elevations):.1f}m")
112
```
113
114
### Batch GPX Processing
115
116
Process multiple GPX files efficiently using batch mode to minimize memory usage.
117
118
**Usage Example:**
119
```python
120
import srtm
121
import gpxpy
122
import os
123
124
# Configure for batch processing
125
elevation_data = srtm.get_data(batch_mode=True)
126
127
gpx_files = ['track1.gpx', 'track2.gpx', 'track3.gpx']
128
129
for gpx_filename in gpx_files:
130
print(f"Processing {gpx_filename}...")
131
132
# Load GPX
133
with open(gpx_filename, 'r') as gpx_file:
134
gpx = gpxpy.parse(gpx_file.read())
135
136
# Add elevations
137
elevation_data.add_elevations(gpx, smooth=True)
138
139
# Save processed GPX
140
output_filename = f"processed_{gpx_filename}"
141
with open(output_filename, 'w') as output_file:
142
output_file.write(gpx.to_xml())
143
144
print(f"Saved {output_filename}")
145
146
print("Batch processing complete")
147
```
148
149
### Advanced GPX Processing
150
151
Combine elevation processing with track analysis and validation.
152
153
**Usage Example:**
154
```python
155
import srtm
156
import gpxpy
157
from datetime import datetime
158
159
elevation_data = srtm.get_data()
160
161
def process_gpx_with_stats(filename):
162
"""Process GPX file and return elevation statistics."""
163
with open(filename, 'r') as gpx_file:
164
gpx = gpxpy.parse(gpx_file.read())
165
166
# Store original elevation count
167
original_elevations = sum(
168
1 for track in gpx.tracks
169
for segment in track.segments
170
for point in segment.points
171
if point.elevation is not None
172
)
173
174
# Add missing elevations with smoothing
175
elevation_data.add_elevations(gpx, only_missing=True, smooth=True)
176
177
# Calculate statistics
178
elevations = []
179
distances = []
180
prev_point = None
181
182
for track in gpx.tracks:
183
for segment in track.segments:
184
for point in segment.points:
185
if point.elevation is not None:
186
elevations.append(point.elevation)
187
188
if prev_point:
189
distance = point.distance_2d(prev_point)
190
if distance:
191
distances.append(distance)
192
prev_point = point
193
194
total_distance = sum(distances) if distances else 0
195
elevation_gain = sum(
196
max(0, elevations[i] - elevations[i-1])
197
for i in range(1, len(elevations))
198
) if len(elevations) > 1 else 0
199
200
return {
201
'filename': filename,
202
'total_points': gpx.get_track_points_no(),
203
'original_elevations': original_elevations,
204
'final_elevations': len(elevations),
205
'min_elevation': min(elevations) if elevations else None,
206
'max_elevation': max(elevations) if elevations else None,
207
'total_distance_km': total_distance / 1000,
208
'elevation_gain_m': elevation_gain
209
}
210
211
# Process multiple files
212
stats = [process_gpx_with_stats(f) for f in ['hike1.gpx', 'hike2.gpx']]
213
214
for stat in stats:
215
print(f"\n{stat['filename']}:")
216
print(f" Points: {stat['total_points']}")
217
print(f" Elevations added: {stat['final_elevations'] - stat['original_elevations']}")
218
print(f" Distance: {stat['total_distance_km']:.1f} km")
219
print(f" Elevation: {stat['min_elevation']:.0f}m - {stat['max_elevation']:.0f}m")
220
print(f" Total gain: {stat['elevation_gain_m']:.0f}m")
221
```
222
223
## Integration with GPXpy
224
225
SRTM.py is designed to work seamlessly with the gpxpy library for GPX file processing:
226
227
**Required Installation:**
228
```bash
229
pip install gpxpy SRTM.py
230
```
231
232
**Basic GPXpy Integration:**
233
```python
234
import gpxpy
235
import srtm
236
237
# Parse GPX from string
238
gpx_string = """<?xml version="1.0"?>
239
<gpx version="1.1" creator="example">
240
<trk>
241
<trkseg>
242
<trkpt lat="45.0" lon="7.0"></trkpt>
243
<trkpt lat="45.1" lon="7.1"></trkpt>
244
</trkseg>
245
</trk>
246
</gpx>"""
247
248
gpx = gpxpy.parse(gpx_string)
249
elevation_data = srtm.get_data()
250
elevation_data.add_elevations(gpx)
251
252
# Output enhanced GPX
253
print(gpx.to_xml())
254
```
255
256
## Performance Considerations
257
258
- **Memory Usage**: Use `batch_mode=True` when processing many large GPX files
259
- **Network Efficiency**: SRTM files are cached locally after first download
260
- **Processing Speed**: Smoothing and interpolation add processing time but improve accuracy
261
- **File Size**: Adding elevations increases GPX file size by approximately 10-20%