Skip to content

Instantly share code, notes, and snippets.

@honza
Created January 19, 2014 12:26
Show Gist options
  • Save honza/8504171 to your computer and use it in GitHub Desktop.
Save honza/8504171 to your computer and use it in GitHub Desktop.
loc2pgx
#!/usr/bin/env python
"""
This script parses a geocaching.loc file and produces GPX files suitable
for loading into a GPS unit.
Usage:
$ ./loc2gpx geocaching.log
It will createa a GPX file for each item in the .loc file. The
filenames are the geocache codes. This is consistent with what
geocaching.com uses when you "Send to GPS".
"""
import sys
from random import randint
import xml.etree.ElementTree as ET
TEMPLATE = """<?xml version="1.0" encoding="utf-8"?>
<gpx xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" version="1.0" creator="Groundspeak, Inc. All Rights Reserved. http://www.groundspeak.com" xsi:schemaLocation="http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd http://www.groundspeak.com/cache/1/0 http://www.groundspeak.com/cache/1/0/cache.xsd" xmlns="http://www.topografix.com/GPX/1/0">
<name>Cache Listing Generated from Geocaching.com</name>
<desc>This is an individual cache generated from Geocaching.com</desc>
<author>Someone From Geocaching.com</author>
<email>[email protected]</email>
<url>http://www.geocaching.com</url>
<urlname>Geocaching - High Tech Treasure Hunting</urlname>
<keywords>cache, geocache</keywords>
<wpt lat="{lat}" lon="{lon}">
<name>{id}</name>
<desc>{name}</desc>
<sym>Geocache</sym>
<type>Geocache|Unknown</type>
<groundspeak:cache id="{num}" available="True" archived="False" xmlns:groundspeak="http://www.groundspeak.com/cache/1/0">
<groundspeak:name>{name}</groundspeak:name>
</groundspeak:cache>
</wpt>
</gpx>"""
def parse_waypoint(w):
wp = {
'num': randint(1000, 10 * 10 * 1000)
}
for c in w.getchildren():
if c.tag == 'name':
wp.update(c.attrib)
wp.update(dict(name=c.text))
if c.tag == 'coord':
wp.update(c.attrib)
return wp
def render_gpx(w):
s = TEMPLATE.format(**w)
filename = '{}.GPX'.format(w['id'])
with open(filename, 'w') as f:
f.write(s)
def main(filename):
d = ET.parse(filename)
root = d.getroot()
w = root.getchildren()
points = map(parse_waypoint, w)
map(render_gpx, points)
if __name__ == '__main__':
main(sys.argv[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment