Last active
September 14, 2020 01:39
-
-
Save rolandcrosby/d5dc0f2595bac274f5860c845b52fb33 to your computer and use it in GitHub Desktop.
merge multiple KML track files from FlightAware into a single file that can be imported into Google My Maps
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from glob import glob | |
from lxml import etree | |
def xpath(el, path): | |
return el.xpath(path, namespaces={ | |
'kml': 'http://www.opengis.net/kml/2.2', | |
'gx': 'http://www.google.com/kml/ext/2.2' | |
}) | |
airports = {} | |
tracks = [] | |
for filename in glob("2020*.xml"): | |
with open(filename) as f: | |
parsed = etree.parse(f, etree.XMLParser(remove_blank_text=True)) | |
dt, _, _ = filename.partition('.') | |
date, _, time = dt.partition('_') | |
root = parsed.xpath('.')[0] | |
for track in xpath(root, '//gx:Track/parent::*'): | |
for name in xpath(track, 'kml:name'): | |
for desc in xpath(track, 'kml:description'): | |
name.text = f"{date} {time} - {desc.text} - {name.text}" | |
tracks.append(track) | |
for airport in xpath(root, '//kml:Point/parent::*'): | |
for name in xpath(airport, 'kml:name'): | |
if name.text not in airports: | |
airports[name.text] = airport | |
with open('template.xml') as f: | |
out = etree.parse(f, etree.XMLParser(remove_blank_text=True)) | |
root = out.xpath('.')[0] | |
nss = root.nsmap | |
nss['kml'] = nss.pop(None) | |
out_doc = out.xpath('//kml:Document', namespaces=nss)[0] | |
for el in tracks: | |
out_doc.append(el) | |
for a, el in airports.items(): | |
if a.startswith('K'): | |
out_doc.append(el) | |
with open('out.kml', 'wb') as outfile: | |
outfile.write(etree.tostring(root)) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="UTF-8"?> | |
<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2"> | |
<Document> | |
<name>N744ST Flight History</name> | |
</Document> | |
</kml> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
to print the KML URLs from the flight history page: