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>
29 </PolyStyle>""" % (c
['PolyStyle']['color'],c
['PolyStyle'].get('colorMode','random')))
30 kml
.write("\n</Style>")
31 folder_name
= data
.get('folder_name',name
)
33 <Folder><name>%s</name>
34 <open>1</open>""" % folder_name
)
35 for idx
, c
in enumerate(data
['contours']):
36 time_begin
= c
['time_begin']
41 <TimeSpan><begin>%s</begin></TimeSpan>
43 <styleUrl>ColorStyle%s</styleUrl>
44 <MultiGeometry>""" % (
45 time_begin
, time_begin
, time_begin
,idx
))
46 for polygon
in c
['polygons']:
50 for segment
in polygon
:
51 kml
.write("\n%s,%s,0" % tuple(segment
))
65 if __name__
== '__main__':
66 print 'Running a self-test case'
68 'name':'selftest.kmz',
69 'folder_name':'Test Perimeters',
71 {'text':'2011-06-28T23:43:00-06:00',
80 'time_begin':'2011-06-28T23:43:00-06:00',
96 {'text':'2011-06-29T23:43:00-06:00',
105 'time_begin':'2011-06-29T23:43:00-06:00',
123 print ('data: ' + json
.dumps(data
,indent
=4, separators
=(',', ': ')))
124 contour2kml(data
,'selftest.kml')
125 print 'open file selftest.kml in Google Earth'