-
Notifications
You must be signed in to change notification settings - Fork 3
/
g2k.py
412 lines (362 loc) · 14.2 KB
/
g2k.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
#!/usr/bin/env python
try:
from osgeo import osr
from osgeo import ogr
except ImportError:
import osr
import ogr
#from OssimPython import OssimHeight
import os.path
import zipfile
def WalkAndTransform( geom,tr ):
if geom.GetGeometryCount() > 0:
for i in range(geom.GetGeometryCount()):
old_geom = geom.GetGeometryRef(i)
new_geom = WalkAndTransform( old_geom )
if new_geom is not old_geom:
geom.SetGeometryDirectly( new_geom )
return geom
for i in range(geom.GetPointCount()):
xyz = (geom.GetX(i), geom.GetY(i), geom.GetZ(i))
if tr == '3D':
xyz = SetOssimHeight( xyz )
if tr == 'offset':
xyz = SetOffset( xyz )
if tr == 'Attribute':
xyz = SetAttributeHeight( xyz )
geom.SetPoint( i, xyz[0], xyz[1], xyz[2] )
return geom
def SetOssimHeight( xyz ):
x = xyz[0]
y = xyz[1]
z = OssimHeight(y,x)
z = float(z) + off
return (float(x),float(y),float(z))
def SetOffset( xyz ):
x = xyz[0]
y = xyz[1]
z = float(off)
return (float(x),float(y),float(z))
def SetAttributeHeight( xyz ):
x = xyz[0]
y = xyz[1]
z = float(AttHeight)
return (float(x),float(y),float(z))
def OpenKml(name, status, description):
openkml = """<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>
<name>%s</name>
<open>%s</open>
<description>%s</description>""" % (name, status, description)
return openkml
def InitStyle(colorlabel,colormode,icon, colorline,tessellate,width,colorpolygon, LabelAlpha, LineAlpha, PolygonAlpha):
labalpha = hex(LabelAlpha)
linalpha = hex(LineAlpha)
polalpha = hex(PolygonAlpha)
labalpha = labalpha.split('x')
linalpha = linalpha.split('x')
polalpha = polalpha.split('x')
labalpha = labalpha[-1]
linalpha = linalpha[-1]
polalpha = polalpha[-1]
if len(labalpha) == 1:
labalpha = str('0')+labalpha
if len(linalpha) == 1:
linalpha = str('0')+linalpha
if len(polalpha) == 1:
polalpha = str('0')+polalpha
colorlabel = colorlabel[1:]
colorlabelR = colorlabel[0:2]
colorlabelG = colorlabel[2:4]
colorlabelB = colorlabel[4:6]
colorlabel = colorlabelB+colorlabelG+colorlabelR
colorlabel = str(labalpha)+colorlabel
colorline = colorline[1:]
colorlineR = colorline[0:2]
colorlineG = colorline[2:4]
colorlineB = colorline[4:6]
colorline = colorlineB+colorlineG+colorlineR
colorline = str(linalpha)+colorline
colorpolygon = colorpolygon[1:]
colorpolygonR = colorpolygon[0:2]
colorpolygonG = colorpolygon[2:4]
colorpolygonB = colorpolygon[4:6]
colorpolygon = colorpolygonB+colorpolygonG+colorpolygonR
colorpolygon = str(polalpha)+colorpolygon
iconname = icon.split('/')[-1]
Style = """<Style id="Mystyle">
<LabelStyle>
<color>%s</color>
<colorMode>%s</colorMode>
<scale>1</scale>
</LabelStyle>
<IconStyle>
<Icon>
<href>%s</href>
</Icon>
</IconStyle>
<LineStyle>
<color>%s</color>
<colorMode>%s</colorMode>
<tessellate>%s</tessellate>
<width>%s</width>
</LineStyle>
<PolyStyle>
<color>%s</color>
<colorMode>%s</colorMode>
</PolyStyle>
</Style>""" % (colorlabel,colormode,iconname, colorline, colormode, tessellate,
width,colorpolygon,colormode)
return Style
def SetPlacemark(namelabels, attributi, lon, lat, alt, rangex, tilt, color):
"""<LookAt>
<longitude>%s</longitude>
<latitude>%s</latitude>
<altitude>%s</altitude>
<range>%s</range>
<tilt>%s</tilt>
<heading>0</heading>
</LookAt> lon, lat, alt, rangex, tilt """
Placemark = """<Placemark>
<name>%s</name>
<description><![CDATA[<color>%s</color><table border="1">%s</table>]]></description>
<visibility>0</visibility>
<styleUrl>#Mystyle</styleUrl>""" % (namelabels, color, attributi)
return Placemark
def OpenPoint(extrude, altitudemode):
openPoint = """<Point>
<extrude>%s</extrude>
<altitudeMode>%s</altitudeMode>
<coordinates>""" % (extrude, altitudemode)
return openPoint
def ClosePoint():
closePoint = """</coordinates>
</Point></Placemark>"""
return closePoint
##########################
def OpenPolygon(extrude, altitudemode):
openPolygon = """<Polygon>
<extrude>%s</extrude>
<altitudeMode>%s</altitudeMode>""" % (extrude, altitudemode)
return openPolygon
def ClosePolygon():
closePolygon = """</Polygon></Placemark>"""
return closePolygon
def OpenOutherBoundary():
OpenOutherBoundary = "<outerBoundaryIs><LinearRing><coordinates>"
return OpenOutherBoundary
def CloseOutherBoundary():
CloseOutheBoundary = "</coordinates></LinearRing></outerBoundaryIs>"
return CloseOutheBoundary
def OpenInnerBoundary():
OpenInnerBoundary = "<innerBoundaryIs><LinearRing><coordinates>"
return OpenInnerBoundary
def CloseInnerBoundary():
CloseInnerrBoundary = "</coordinates></LinearRing></innerBoundaryIs>"
return CloseInnerrBoundary
###########################
def CloseKml():
CloseKml = """</Document></kml>"""
return CloseKml
def addoverlay(self, name, outfile):
kml_overlay = """<ScreenOverlay>
<name>%s</name>
<visibility>0</visibility>
<Icon>
<href>%s</href>
</Icon>
<overlayXY x="0" y="1" xunits="fraction" yunits="fraction"/>
<screenXY x="0" y="1" xunits="fraction" yunits="fraction"/>
<rotationXY x="0" y="0" xunits="fraction" yunits="fraction"/>
<size x="0.5" y="0" xunits="fraction" yunits="fraction"/>
</ScreenOverlay>""" % (name, outfile)
return kml_overlay
def OpenLine(extrude, tessellate, altitudemode):
openLine = """<LineString>
<extrude>%s</extrude>
<tessellate>%s</tessellate>
<altitudeMode>%s</altitudeMode>
<coordinates>""" % (extrude, tessellate, altitudemode)
return openLine
def CloseLine():
closeLine = """</coordinates>
</LineString></Placemark>"""
return closeLine
def compress_kml(outfile,icon):
outfilename = outfile.split('/')
outfilename = outfilename[-1]
kmz = outfile.split('.')[0]+'.kmz'
zip = zipfile.ZipFile(str(kmz), 'w')
zip.write(str(outfile))
##zip.write(str(icontosave))
zip.close
def GrassToKml(ExtrudeType, featuretype, infile, outfile, num_lay, name, status,
description, colorlabel, labelscale, icon, tessellate, extrude,
width, colorline, colormode, colorpolygon, namelabel, lon, lat,
alt, rangex, tilt, altitudemode, offset,heightfield,LabelAlpha,
LineAlpha, PolygonAlpha, delshp=False, haveOverlay=False, colorattributefield="color" ):
global off
global namelabels
global AttHeight
off = offset
out00 = OpenKml(name, status, description)
out11 = InitStyle(colorlabel, colormode, icon, colorline, tessellate, width,
colorpolygon, LabelAlpha, LineAlpha, PolygonAlpha)
f=open(outfile, 'w')
f.write(out00)
f.write(out11)
##create overlay
if haveOverlay:
overlay_str = kmloverlay("Overlay", outfile)
f.write(overlay_str)
for l in range(num_lay):
in_ds = ogr.Open( str(infile), update = 1 )
in_layer = in_ds.GetLayer( l )
if in_layer is not None:
in_defn = in_layer.GetLayerDefn()
in_field_count = in_defn.GetFieldCount()
in_feat = in_layer.GetNextFeature()
in_sr = in_layer.GetSpatialRef()
out_sr = osr.SpatialReference()
out_sr.ImportFromEPSG(4326)
attr = in_layer.GetLayerDefn().GetFieldCount()
while in_feat is not None:
geom = in_feat.GetGeometryRef()
tipo = geom.GetGeometryType()
geom.AssignSpatialReference(in_sr)
geom.TransformTo(out_sr)
attributi = []
pcolor = ""
field = dict()
for i in range(attr):
attname = in_layer.GetLayerDefn().GetFieldDefn(i).GetName()
attvalue = in_feat.GetField(in_layer.GetLayerDefn().GetFieldDefn(i).GetName())
field[attname] = attvalue
pcolor = ""
if attname==colorattributefield:
pcolor = field[colorattributefield]
attributi.append(str('<TR><TD>')+str(attname)+str(':')+str('</TD><TD>')+str(attvalue)+str('</TD>'))
##print attributi
namelabels = field.get(str(namelabel))
##print namelabels
AttHeight = field.get(str(heightfield))
attributi = str(attributi)
attributi = attributi.replace('[','')
attributi = attributi.replace(']','')
attributi = attributi.replace("'",'')
attributi = attributi.replace(", ",'')
coords = str(geom)
##print coords
holed = '),('
if holed not in coords:
coords = coords.strip()
coords = coords.replace('(','')
coords = coords.replace(')','')
coords = coords.replace('L','')
coords = coords.replace('I','')
coords = coords.replace('N','')
coords = coords.replace('E','')
coords = coords.replace('S','')
coords = coords.replace('T','')
coords = coords.replace('R','')
coords = coords.replace('G','')
coords = coords.replace('P','')
coords = coords.replace('O','')
coords = coords.replace('Y','')
coords = coords.strip()
coords = coords.split(',')
number = len(coords)
for i in range(number):
coords[i] = coords[i].split(' ')
coords[i] = ','.join(coords[i])
coords = str(coords)
coords = coords.replace("'",'')
coords = coords.replace(", ",' ')
coords = str(coords)
coords = coords.replace('[','')
coords = coords.replace(']','')
if featuretype == 'polygon':
opp = OpenOutherBoundary()
clp = CloseOutherBoundary()
coords = str(opp)+coords+str(clp)
#print coords
if holed in coords:
coords = coords.strip()
coords = coords.replace('L','')
coords = coords.replace('I','')
coords = coords.replace('N','')
coords = coords.replace('E','')
coords = coords.replace('S','')
coords = coords.replace('T','')
coords = coords.replace('R','')
coords = coords.replace('G','')
coords = coords.replace('P','')
coords = coords.replace('O','')
coords = coords.replace('Y','')
coords = coords.strip()
list_hole = coords.split('),(')
num_hole = len(list_hole)
##print num_hole
jk = []
for i in range(num_hole):
coordsh = list_hole[i]
coordsh = coordsh.replace('(','')
coordsh = coordsh.replace(')','')
coordsh = coordsh.split(',')
numberh = len(coordsh)
for j in range(numberh):
coordsh[j] = coordsh[j].split(' ')
coordsh[j] = ','.join(coordsh[j])
coordsh = str(coordsh)
coordsh = coordsh.replace("'",'')
coordsh = coordsh.replace(", ",' ')
coordsh = coordsh.replace('[','')
coordsh = coordsh.replace(']','')
oph = OpenInnerBoundary()
clh = CloseInnerBoundary()
if i == 0:
oph = OpenOutherBoundary()
clh = CloseOutherBoundary()
coordsh = str(oph)+coordsh+str(clh)
jk.append(coordsh)
jk = str(jk)
jk = jk.strip()
jk = jk.replace('[','')
jk = jk.replace(']','')
#jk = jk.replace(',','')
jk = jk.replace("'",'')
jk = jk.replace(">, <",'><')
jk = jk.strip()
coords = jk
Place = SetPlacemark(namelabels, attributi, lon, lat, alt, rangex, tilt, pcolor)
if featuretype == 'polygon':
Feature = OpenPolygon(extrude, altitudemode)
if featuretype == 'line':
Feature = OpenLine(extrude, tessellate, altitudemode)
if featuretype == 'point':
Feature = OpenPoint(extrude, altitudemode)
f.write(Place)
f.write(Feature)
out3 = coords
f.write(out3)
if featuretype == 'polygon':
out4 = ClosePolygon()
if featuretype == 'line':
out4 = CloseLine()
if featuretype == 'point':
out4 = ClosePoint()
f.write(out4)
in_feat = in_layer.GetNextFeature()
in_ds.Destroy()
out5 = CloseKml()
f.write(out5)
f.close()
kmz = compress_kml(str(outfile),str(icon))
if delshp:
delfilecmd = "rm -f " + infile
print "not deleting now " + delfilecmd
##os.system(delfilecmd)
if __name__ == '__main__':
for arg in sys.argv[1:]:
grass2kml(infile,num_lay)