User:Avena701/osm2gpx.py

From OpenStreetMap Wiki
Jump to navigation Jump to search
#!/usr/bin/python
from osmread import parse_file, Node
import gpxpy
import gpxpy.gpx
import sys

gpx = gpxpy.gpx.GPX()

if len(sys.argv) != 3:
	print('Please call: python osm2gpx.px input.osm output.gpx')
	sys.exit()

infn = sys.argv[1];
outfn = sys.argv[2];

for entity in parse_file(infn):
    if isinstance(entity, Node):
	lat = entity.lat
	lon = entity.lon
	
	if 'name' in entity.tags:
		name = entity.tags['name']
	else:	
		name = ''
	
	desc = ''
	for (tag, value) in entity.tags.items():
		if tag != 'name':
			desc = '%s%s=%s\n' %(desc, tag, value)

	newGPXWaypoint = gpxpy.gpx.GPXWaypoint(lat, lon, name=name, description=desc)
	gpx.waypoints.append(newGPXWaypoint)
    else:
	print('Found way or relation: Please provide osm file with nodes only')



fid = open(outfn, 'w')
fid.write(gpx.to_xml())
fid.close()