3 def contour2kml(data
,kml_path
):
4 with
open(kml_path
,'w') as kml
:
5 name
= data
.get('name','No Name')
6 kml
.write("""<?xml version="1.0" encoding="UTF-8"?>\n""")
7 kml
.write("""<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2" xmlns:kml="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom">\n""")
8 kml
.write("""<Document><name>%s</name>\n""" % name
)
9 # write all styles first
10 for idx
, c
in enumerate(data
['contours']):
11 kml
.write("""<Style id="ColorStyle%s">""" % idx
)
12 if 'text' in c
and c
['text'] is not None:
16 </BalloonStyle>""" % c
['text'])
17 if 'LineStyle' in c
and c
['LineStyle'] is not None:
22 </LineStyle>""" % (c
['LineStyle']['color'],c
['LineStyle'].get('width',3)))
23 if 'PolyStyle' in c
and c
['PolyStyle'] is not None:
27 <colorMode>%s</colorMode>
28 </PolyStyle>""" % (c
['PolyStyle']['color'],c
['PolyStyle'].get('colorMode','random')))
29 kml
.write("\n</Style>")
30 folder_name
= data
.get('folder_name',name
)
32 <Folder><name>%s</name>
33 <open>1</open>""" % folder_name
)
34 for idx
, c
in enumerate(data
['contours']):
35 time_begin
= c
['time_begin']
40 <TimeSpan><begin>%s</begin></TimeSpan>
42 <styleUrl>ColorStyle%s</styleUrl>
43 <MultiGeometry>""" % (
44 time_begin
, time_begin
, time_begin
,idx
))
45 for polygon
in c
['polygons']:
51 for segment
in polygon
:
52 kml
.write("\n%s,%s,0" % tuple(segment
))
68 if __name__
== '__main__':
69 print 'Running a self-test case'
71 'name':'selftest.kmz',
72 'folder_name':'Test Perimeters',
74 {'text':'2011-06-28T23:43:00-06:00',
83 'time_begin':'2011-06-28T23:43:00-06:00',
99 {'text':'2011-06-29T23:43:00-06:00',
108 'time_begin':'2011-06-29T23:43:00-06:00',
126 print ('data: ' + json
.dumps(data
,indent
=4, separators
=(',', ': ')))
127 contour2kml(data
,'selftest.kml')
128 print 'open file selftest.kml in Google Earth'