Skip to content

Instantly share code, notes, and snippets.

@kevin1024
Created March 5, 2014 23:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kevin1024/9379306 to your computer and use it in GitHub Desktop.
Save kevin1024/9379306 to your computer and use it in GitHub Desktop.
kml to geojson
from xml.etree import ElementTree
from shapely.geometry import Polygon, Point
import json
poly_table = []
data = open('/tmp/chicago.kml')
tree = ElementTree.parse(data)
namespace = tree.getroot().tag[1:].split("}")[0]
placemarks = tree.findall(".//{%s}Placemark" % namespace)
for p in placemarks:
for d in p.findall(".//{%s}Data" % namespace):
if d.attrib.get('name') == 'OBJECTID':
name = d.find('.//{%s}value' % namespace).text
coord_text = p.find('.//{%s}coordinates' % namespace).text
coord_pairs = coord_text.split(' ')
coords = [z.split(',')[0:2] for z in coord_pairs]
polygon = [(float(x[0]),float(x[1])) for x in coords]
poly_table.append((polygon,name))
features = []
for polygon,name in poly_table:
new_feature = {
'type':'Feature',
'geometry': {
'type':'Polygon',
'coordinates': [polygon]
},
'properties': {
'neighborhood': name,
},
}
features.append(new_feature)
out = {
'type':'FeatureCollection',
'features': features,
}
print json.dumps(out)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment