1 | #!/bin/env python
|
---|
2 |
|
---|
3 | import sys
|
---|
4 | args = sys.argv
|
---|
5 | if not args[1:]:
|
---|
6 | print "Usage: python KML2WKT.py <filename>.kml"
|
---|
7 | sys.exit(1)
|
---|
8 |
|
---|
9 | from lxml import etree
|
---|
10 | from keytree.factory import *
|
---|
11 | from shapely.geometry import asShape
|
---|
12 | from shapely.wkt import dumps as wkt_dumps
|
---|
13 |
|
---|
14 | GEOM_TYPES = [
|
---|
15 | "Point",
|
---|
16 | "LineString",
|
---|
17 | "Polygon",
|
---|
18 | #"LinearRing",
|
---|
19 | #"MultiGeometry" # Not currently supported
|
---|
20 | ]
|
---|
21 |
|
---|
22 | inputFilename = args[1]
|
---|
23 | outputFilename = "%s.csv" % inputFilename[:-4]
|
---|
24 |
|
---|
25 | inputFile = open(inputFilename, "rb")
|
---|
26 | data = inputFile.read()
|
---|
27 | inputFile.close()
|
---|
28 |
|
---|
29 | root = etree.fromstring(data)
|
---|
30 | kmlns = root.tag.split("}")[0][1:]
|
---|
31 | placemarks = root.findall(".//{%s}Placemark" % kmlns)
|
---|
32 |
|
---|
33 | output = u"Name,Comments,Lat,Lon,WKT\n"
|
---|
34 | for 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 |
|
---|
70 | import codecs
|
---|
71 |
|
---|
72 | outputFile = codecs.open(outputFilename, encoding="utf-8", mode="w")
|
---|
73 | outputFile.write(output)
|
---|
74 | outputFile.close()
|
---|