Skip to content

Instantly share code, notes, and snippets.

@bieli
Last active July 16, 2017 03:21
Show Gist options
  • Save bieli/c88b002ce0cb8000f8570f4fb0037087 to your computer and use it in GitHub Desktop.
Save bieli/c88b002ce0cb8000f8570f4fb0037087 to your computer and use it in GitHub Desktop.
GpxToGEOJsonConverter
import glob
import gpxpy
import gpxpy.gpx
from geojson import Feature, LineString, FeatureCollection
from datetime import datetime
class GpxToGEOJsonConverter:
def to_timestamp(self, dt, epoch=datetime(1970, 1, 1)):
td = dt - epoch
return (td.microseconds + (td.seconds + td.days * 86400) * 10 ** 6) / 10 ** 6
def get_data_from_xml_file(self, file_name):
gpx_file = open(file_name, 'r')
gpx = gpxpy.parse(gpx_file)
data = []
for track in gpx.tracks:
for segment in track.segments:
for point in segment.points:
data.append({"lat": point.latitude,
"lon": point.longitude,
"ts": self.to_timestamp(point.time),
"ele": point.elevation})
return data
def convert_gpx_file(self, file_name):
dataset = self.get_data_from_xml_file(file_name)
timestamps = []
elevations = []
points = []
for data in dataset:
# print(data)
points.append((data['lon'], data['lat']))
timestamps.append(int(data["ts"]))
elevations.append(data["ele"])
props = {
"distance": None,
"duration": None,
"energy_burned": None,
"altitude": None,
"ascent": None,
"max_speed": None,
"activity_type": "CAR",
"timestamps": timestamps,
"elevations": elevations
}
my_line = LineString(points)
my_feature = Feature(geometry=my_line, properties=props)
json = FeatureCollection([my_feature])
# print(json)
return json
def convert_gpx_files(self, files_names_pattern="*.gpx"):
files = glob.glob(files_names_pattern)
for file_name in files:
print("file_name: ", file_name)
json = self.convert_gpx_file(file_name)
with open(file_name + ".json", "w") as outfile:
outfile.write(str(json))
c = GpxToGEOJsonConverter()
c.convert_gpx_files()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment