UserGuidelines/GIS/Data: KML2WKT.py

File KML2WKT.py, 1.9 KB (added by Fran Boon, 7 years ago)
Line 
1#!/bin/env python
2
3import sys
4args = sys.argv
5if not args[1:]:
6 print "Usage: python KML2WKT.py <filename>.kml"
7 sys.exit(1)
8
9from lxml import etree
10from keytree.factory import *
11from shapely.geometry import asShape
12from shapely.wkt import dumps as wkt_dumps
13
14GEOM_TYPES = [
15 "Point",
16 "LineString",
17 "Polygon",
18 #"LinearRing",
19 #"MultiGeometry" # Not currently supported
20 ]
21
22inputFilename = args[1]
23outputFilename = "%s.csv" % inputFilename[:-4]
24
25inputFile = open(inputFilename, "rb")
26data = inputFile.read()
27inputFile.close()
28
29root = etree.fromstring(data)
30kmlns = root.tag.split("}")[0][1:]
31placemarks = root.findall(".//{%s}Placemark" % kmlns)
32
33output = u"Name,Comments,Lat,Lon,WKT\n"
34for placemark in placemarks:
35 name = placemark.find("{%s}name" % kmlns).text
36 desc = placemark.find("{%s}description" % kmlns).text
37
38 output += unicode('"')
39 output += name
40 output += unicode('"')
41 output += unicode(",")
42
43 output += unicode('"')
44 output += desc
45 output += unicode('"')
46 output += unicode(",")
47
48 for geom_type in GEOM_TYPES:
49 tag = "{%s}%s" % (kmlns, geom_type)
50 geom_element = placemark.findall(".//%s" % tag)
51 if geom_element == []:
52 continue
53 else:
54 g = geometry(geom_element[0])
55
56 shape = asShape(g)
57 if geom_type == "Point":
58 output += unicode(shape.y)
59 output += unicode(",")
60 output += unicode(shape.x)
61 output += unicode(",")
62 output += unicode("\n")
63 else:
64 wkt = wkt_dumps(shape)
65 output += unicode(",")
66 output += unicode(",")
67 output += unicode(wkt)
68 output += unicode("\n")
69
70import codecs
71
72outputFile = codecs.open(outputFilename, encoding="utf-8", mode="w")
73outputFile.write(output)
74outputFile.close()