Skip to content

Instantly share code, notes, and snippets.

@dansimau
Created October 18, 2018 08:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dansimau/80d3e2ad558ef03e490d9ff2aeb8c82e to your computer and use it in GitHub Desktop.
Save dansimau/80d3e2ad558ef03e490d9ff2aeb8c82e to your computer and use it in GitHub Desktop.
Convert starred places from Google Maps to a KML document (via Google Takeout).
"""
Takes a list of JSON files from Google Takeout's "Maps (Your Places)" and
converts them into KML documents.
"""
import json
import os
import simplekml
import sys
import unicodedata
import xml.sax.saxutils
def xml_escape(s):
"""
Prepares a string for inclusion in an XML document.
"""
if s is not None:
return xml.sax.saxutils.escape(s)
def get(user_dict, path):
"""
Traverses down into multiple levels of dicts and returns the value at the
end of path. path is a list of keys to drill down in to.
"""
val = user_dict
for x in path:
try:
val = val[x]
except KeyError:
return None
return val
if len(sys.argv) < 2:
print("Usage: %s <file [...]>" % os.path.basename(sys.argv[0]), file=sys.stderr)
sys.exit(1)
for fname in sys.argv[1:]:
# New KML document
kml = simplekml.Kml()
with open(fname) as f:
data = json.load(f)
# Read JSON data and convert places into KML points
for place in data["features"]:
point = kml.newpoint(coords=[(
float(place["geometry"]["coordinates"][0]),
float(place["geometry"]["coordinates"][1]))
])
point.name = xml_escape(get(place, ["properties", "Location", "Business Name"]))
point.address = xml_escape(get(place, ["properties", "Location", "Address"]))
# Determine output filename and check for existing file
base_fname, _ = os.path.splitext(os.path.basename(fname))
output_fname = "%s.%s" % (base_fname, "kml")
if os.path.exists(output_fname):
user_data = input("File \"%s\" exists. Overwrite? [y/N] " % output_fname)
if not user_data.lower() == "y":
print("Aborting.", file=sys.stdout)
sys.exit(1)
# Write output file
kml.save(output_fname)
print("Wrote: %s" % output_fname)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment