def read_track_from_gpx(self, filepath, filebase, trackfolder, colourIndex): """ Read a single GPX file and extract the track(s), converting them to a list of KML tracks. Append or replace each track in the trackfolder. This fills the trackfolder in makekml. Arguments: filepath: the full path to the GPX file filebase: the basename of the GPX file, used to name the KML tracks trackfolder: a KML.Folder to hold track Placemarks colourIndex: the next colourIndex to use when creating a linestyle On successful exit, trackfolder and colourIndex will have been updated. """ args = self.config['arguments'] gpxtree = etree.parse(filepath).getroot() namespace = gpxtree.nsmap[None] if self.verbosity > 1: print('namespace for ' + filepath + ': ' + namespace, file=sys.stderr) print('{%s}trk' % namespace, file=sys.stderr) print(namespace + 'trk', file=sys.stderr) for gpxtrack in gpxtree.getiterator('{%s}trk' % namespace): print('got here', file=sys.stderr) # Extract the track name from the GPX track try: trackname = gpxtrack.find('{%s}name' % namespace).text except: print('track does not have name in ' + filepath, file=sys.stderr) trackname = filebase print('trackname = ' + trackname, file=sys.stderr) # does a Placemark already exist with this name? placemark = None for pm in trackfolder.findall('GX.Placemark'): if pm.find('KML.name').text == trackname: placemark = pm break if 'replace' in args and args['replace']: trackfolder.drop(placemark) placemark = None if not placemark: # Create a new Placemark to hold the KML track(s) colourID = '#colour' + str(self.colourIndex) self.colourIndex = (self.colourIndex + 1) % self.colourSetLen placemark = KML.Placemark( KML.visibility('1'), KML.name(trackname), KML.description(trackname + ' from ' + filebase), KML.styleUrl(colourID)) trackfolder.append(placemark) tracklist = [] for gpxtrkseg in gpxtrack.getiterator('{%s}trkseg' % namespace): # A GPX trkseg translates into aGX.track kmltrack = GX.Track(KML.altitudeMode('clampToGround')) whenlist = [] coordlist = [] for gpxtrkpoint in gpxtrkseg: lat = gpxtrkpoint.attrib['lat'] lon = gpxtrkpoint.attrib['lon'] alt = gpxtrkpoint.find('{%s}ele' % namespace).text time = gpxtrkpoint.find('{%s}time' % namespace).text whenlist.append(GX.when(time)) coordlist.append( GX.coord('{0} {1} {2}'.format(lon, lat, alt))) for w in whenlist: kmltrack.append(w) for c in coordlist: kmltrack.append(c) tracklist.append(kmltrack) if tracklist: if len(tracklist) > 1: multitrack = GX.MultiTrack() for t in tracklist: multitrack.append(t) placemark.append(multitrack) else: placemark.append(tracklist[0]) else: print('no tracks found in ' + filepath, file=sys.stderr)