Skip to content

Instantly share code, notes, and snippets.

@craSH
Created March 14, 2017 09:58
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 craSH/693d19d360026e122a181c59a015a0f3 to your computer and use it in GitHub Desktop.
Save craSH/693d19d360026e122a181c59a015a0f3 to your computer and use it in GitHub Desktop.
tripcreator-manipulator
#!/usr/bin/env python
"""
Parse a TripCreator JSON file and emit a KML file.
Example: https://widgets.tripcreator.com/gas-stations-prices-iceland-map/tripcreator-gas-prices-iceland.json
Taken from the widget on this page: http://luxeadventuretraveler.com/tips-for-driving-icelands-ring-road-winter/
Copyleft 2017 Ian Gallagher <crash@neg9.org>
"""
import json
import os
import simplekml
import sys
from HTMLParser import HTMLParser
def parse_command_line():
import argparse
parser = argparse.ArgumentParser()
# (Required) positional arguments
parser.add_argument("trip_creator", type=str,
help="Source TripCreator JSON.")
parser.add_argument("output_kml", type=str,
help="Output KML Path.")
args = parser.parse_args()
# All done, return the args object in case it's wanted
return args
class MLStripper(HTMLParser):
"""
Taken from https://stackoverflow.com/questions/753052/strip-html-from-strings-in-python
"""
def __init__(self):
self.reset()
self.fed = []
def handle_data(self, d):
self.fed.append(d)
def get_data(self):
return ''.join(self.fed)
def strip_tags(html):
s = MLStripper()
s.feed(html)
return s.get_data()
def read_tc(tc_json):
with open(tc_json, 'r') as fh:
data = fh.read()
return json.loads(data)
def parse_points(tc_json):
"""
Parse points from JSON and return a simplekml object
"""
kml = simplekml.Kml()
kml.document.name = tc_json['id']
features = tc_json['features']
for feature in features:
feature_title = feature['properties']['title']
feature_descr = strip_tags(feature['properties']['description']).replace(' Currency & unit conversion', '')
feature_lat, feature_lon = feature['geometry']['coordinates']
point_name = feature_title
point_descr = feature_descr
point_coords = [(feature_lat, feature_lon)]
# GAIA GPS Doesn't parse out the descripion, so just stuff it all in to the name as well
point_name = u"{0} ({1})".format(feature_title, feature_descr)
kml.newpoint(name=point_name, description=point_descr, coords=point_coords)
return kml
def main():
args = parse_command_line()
tc_json = read_tc(args.trip_creator)
kml = parse_points(tc_json)
kml.save(args.output_kml)
print "Successfully wrote KML output to: {0}".format(args.output_kml)
return(0)
if '__main__' == __name__:
sys.exit(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment