/
kml.py
1532 lines (1344 loc) · 52.4 KB
/
kml.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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
# Copyright (C) 2012 Christian Ledermann
#
# This library is free software; you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation; either version 2.1 of the License, or (at your option)
# any later version.
#
# This library is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
"""
KML is an open standard officially named the OpenGIS KML Encoding Standard
(OGC KML). It is maintained by the Open Geospatial Consortium, Inc. (OGC).
The complete specification for OGC KML can be found at
http://www.opengeospatial.org/standards/kml/.
The complete XML schema for KML is located at
http://schemas.opengis.net/kml/.
"""
try:
import urlparse
except ImportError:
import urllib.parse as urlparse # Python 3
import warnings
# from .geometry import Point, LineString, Polygon
# from .geometry import MultiPoint, MultiLineString, MultiPolygon
# from .geometry import LinearRing
from .geometry import Geometry
from datetime import datetime, date
# note that there are some ISO 8601 timeparsers at pypi
# but in my tests all of them had some errors so we rely on the
# tried and tested dateutil here which is more stable. As a side effect
# we can also parse non ISO compliant dateTimes
import dateutil.parser
import logging
logger = logging.getLogger('fastkml.kml')
from .config import etree
from .base import _BaseObject, _XMLObject
from .styles import StyleUrl, Style, StyleMap, _StyleSelector
import fastkml.atom as atom
# import fastkml.gx as gx
import fastkml.config as config
try:
unicode
except NameError:
# Python 3
basestring = unicode = str
class KML(object):
""" represents a KML File """
_features = []
ns = None
def __init__(self, ns=None):
""" The namespace (ns) may be empty ('') if the 'kml:' prefix is
undesired. Note that all child elements like Document or Placemark need
to be initialized with empty namespace as well in this case.
"""
self._features = []
if ns is None:
self.ns = config.KMLNS
else:
self.ns = ns
def from_string(self, xml_string):
""" create a KML object from a xml string"""
if config.LXML:
element = etree.fromstring(
xml_string,
parser=etree.XMLParser(huge_tree=True)
)
else:
element = etree.XML(xml_string)
if element.tag.endswith('kml'):
ns = element.tag.rstrip('kml')
documents = element.findall('%sDocument' % ns)
for document in documents:
feature = Document(ns)
feature.from_element(document)
self.append(feature)
folders = element.findall('%sFolder' % ns)
for folder in folders:
feature = Folder(ns)
feature.from_element(folder)
self.append(feature)
placemarks = element.findall('%sPlacemark' % ns)
for placemark in placemarks:
feature = Placemark(ns)
feature.from_element(placemark)
self.append(feature)
else:
raise TypeError
def etree_element(self):
# self.ns may be empty, which leads to unprefixed kml elements.
# However, in this case the xlmns should still be mentioned on the kml
# element, just without prefix.
if not self.ns:
root = etree.Element('%skml' % self.ns)
root.set('xmlns', config.KMLNS[1:-1])
else:
if config.LXML:
root = etree.Element(
'%skml' % self.ns,
nsmap={None: self.ns[1:-1]}
)
else:
root = etree.Element('%skml' % self.ns)
for feature in self.features():
root.append(feature.etree_element())
return root
def to_string(self, prettyprint=False):
""" Return the KML Object as serialized xml """
if config.LXML and prettyprint:
return etree.tostring(
self.etree_element(),
encoding='utf-8',
pretty_print=True).decode('UTF-8')
else:
return etree.tostring(
self.etree_element(),
encoding='utf-8').decode('UTF-8')
def features(self):
""" iterate over features """
for feature in self._features:
if isinstance(feature, (Document, Folder, Placemark)):
yield feature
else:
raise TypeError(
"Features must be instances of "
"(Document, Folder, Placemark)"
)
def append(self, kmlobj):
""" append a feature """
if isinstance(kmlobj, (Document, Folder, Placemark)):
self._features.append(kmlobj)
else:
raise TypeError(
"Features must be instances of (Document, Folder, Placemark)")
class _Feature(_BaseObject):
"""
abstract element; do not create
subclasses are:
* Container (Document, Folder)
* Placemark
* Overlay
Not Implemented Yet:
* NetworkLink
"""
name = None
# User-defined text displayed in the 3D viewer as the label for the
# object (for example, for a Placemark, Folder, or NetworkLink).
visibility = 1
# Boolean value. Specifies whether the feature is drawn in the 3D
# viewer when it is initially loaded. In order for a feature to be
# visible, the <visibility> tag of all its ancestors must also be
# set to 1.
isopen = 0
# Boolean value. Specifies whether a Document or Folder appears
# closed or open when first loaded into the Places panel.
# 0=collapsed (the default), 1=expanded.
_atom_author = None
# KML 2.2 supports new elements for including data about the author
# and related website in your KML file. This information is displayed
# in geo search results, both in Earth browsers such as Google Earth,
# and in other applications such as Google Maps.
_atom_link = None
# Specifies the URL of the website containing this KML or KMZ file.
_address = None
# A string value representing an unstructured address written as a
# standard street, city, state address, and/or as a postal code.
# You can use the <address> tag to specify the location of a point
# instead of using latitude and longitude coordinates.
_phoneNumber = None
# A string value representing a telephone number.
# This element is used by Google Maps Mobile only.
_snippet = None # XXX
# _snippet is eiter a tuple of a string Snippet.text and an integer
# Snippet.maxLines or a string
#
# A short description of the feature. In Google Earth, this
# description is displayed in the Places panel under the name of the
# feature. If a Snippet is not supplied, the first two lines of
# the <description> are used. In Google Earth, if a Placemark
# contains both a description and a Snippet, the <Snippet> appears
# beneath the Placemark in the Places panel, and the <description>
# appears in the Placemark's description balloon. This tag does not
# support HTML markup. <Snippet> has a maxLines attribute, an integer
# that specifies the maximum number of lines to display.
description = None
# User-supplied content that appears in the description balloon.
_styleUrl = None
# URL of a <Style> or <StyleMap> defined in a Document.
# If the style is in the same file, use a # reference.
# If the style is defined in an external file, use a full URL
# along with # referencing.
_styles = None
# One or more Styles and StyleMaps can be defined to customize the
# appearance of any element derived from Feature or of the Geometry
# in a Placemark.
# A style defined within a Feature is called an "inline style" and
# applies only to the Feature that contains it. A style defined as
# the child of a <Document> is called a "shared style." A shared
# style must have an id defined for it. This id is referenced by one
# or more Features within the <Document>. In cases where a style
# element is defined both in a shared style and in an inline style
# for a Feature—that is, a Folder, GroundOverlay, NetworkLink,
# Placemark, or ScreenOverlay—the value for the Feature's inline
# style takes precedence over the value for the shared style.
_time_span = None
# Associates this Feature with a period of time.
_time_stamp = None
# Associates this Feature with a point in time.
# TODO Region = None
# Features and geometry associated with a Region are drawn only when
# the Region is active.
# TODO ExtendedData = None
# Allows you to add custom data to a KML file. This data can be
# (1) data that references an external XML schema,
# (2) untyped data/value pairs, or
# (3) typed data.
# A given KML Feature can contain a combination of these types of
# custom data.
#
# (2) is already implemented, see UntypedExtendedData
#
# <Metadata> (deprecated in KML 2.2; use <ExtendedData> instead)
extended_data = None
def __init__(
self, ns=None, id=None, name=None, description=None,
styles=None, styleUrl=None, extended_data=None
):
super(_Feature, self).__init__(ns, id)
self.name = name
self.description = description
self.styleUrl = styleUrl
self._styles = []
if styles:
for style in styles:
self.append_style(style)
self.extended_data = extended_data
@property
def styleUrl(self):
""" Returns the url only, not a full StyleUrl object.
if you need the full StyleUrl object use _styleUrl """
if isinstance(self._styleUrl, StyleUrl):
return self._styleUrl.url
@styleUrl.setter
def styleUrl(self, styleurl):
""" you may pass a StyleUrl Object, a string or None """
if isinstance(styleurl, StyleUrl):
self._styleUrl = styleurl
elif isinstance(styleurl, basestring):
s = StyleUrl(self.ns, url=styleurl)
self._styleUrl = s
elif styleurl is None:
self._styleUrl = None
else:
raise ValueError
@property
def timeStamp(self):
""" This just returns the datetime portion of the timestamp"""
if self._time_stamp is not None:
return self._time_stamp.timestamp[0]
@timeStamp.setter
def timeStamp(self, dt):
if dt is None:
self._time_stamp = None
else:
self._time_stamp = TimeStamp(timestamp=dt)
if self._time_span is not None:
logger.warn('Setting a TimeStamp, TimeSpan deleted')
self._time_span = None
@property
def begin(self):
if self._time_span is not None:
return self._time_span.begin[0]
@begin.setter
def begin(self, dt):
if self._time_span is None:
self._time_span = TimeSpan(begin=dt)
else:
if self._time_span.begin is None:
self._time_span.begin = [dt, None]
else:
self._time_span.begin[0] = dt
if self._time_stamp is not None:
logger.warn('Setting a TimeSpan, TimeStamp deleted')
self._time_stamp = None
@property
def end(self):
if self._time_span is not None:
return self._time_span.end[0]
@end.setter
def end(self, dt):
if self._time_span is None:
self._time_span = TimeSpan(end=dt)
else:
if self._time_span.end is None:
self._time_span.end = [dt, None]
else:
self._time_span.end[0] = dt
if self._time_stamp is not None:
logger.warn('Setting a TimeSpan, TimeStamp deleted')
self._time_stamp = None
@property
def link(self):
return self._atom_link.href
@link.setter
def link(self, url):
if isinstance(url, basestring):
self._atom_link = atom.Link(href=url)
elif isinstance(url, atom.Link):
self._atom_link = url
elif url is None:
self._atom_link = None
else:
raise TypeError
@property
def author(self):
if self._atom_author:
return self._atom_author.name
@author.setter
def author(self, name):
if isinstance(name, atom.Author):
self._atom_author = name
elif isinstance(name, basestring):
if self._atom_author is None:
self._atom_author = atom.Author(name=name)
else:
self._atom_author.name = name
elif name is None:
self._atom_author = None
else:
raise TypeError
def append_style(self, style):
""" append a style to the feature """
if isinstance(style, _StyleSelector):
self._styles.append(style)
else:
raise TypeError
def styles(self):
""" iterate over the styles of this feature """
for style in self._styles:
if isinstance(style, _StyleSelector):
yield style
else:
raise TypeError
@property
def snippet(self):
if self._snippet:
if isinstance(self._snippet, dict):
text = self._snippet.get('text')
if text:
if not (isinstance(text, basestring)):
raise TypeError("text should be of"
"type basestring")
max_lines = self._snippet.get('maxLines', None)
if max_lines is None:
return {'text': text}
elif int(max_lines) > 0:
# if maxLines <=0 ignore it
return {'text': text, 'maxLines': max_lines}
elif isinstance(self._snippet, basestring):
return self._snippet
else:
raise ValueError(
"Snippet must be dict of "
"{'text':t, 'maxLines':i} or string"
)
@snippet.setter
def snippet(self, snip=None):
self._snippet = {}
if isinstance(snip, dict):
self._snippet['text'] = snip.get('text')
max_lines = snip.get('maxLines')
if max_lines is not None:
self._snippet['maxLines'] = int(snip['maxLines'])
elif isinstance(snip, basestring):
self._snippet['text'] = snip
elif snip is None:
self._snippet = None
else:
raise ValueError(
"Snippet must be dict of {'text':t, 'maxLines':i} or string"
)
@property
def address(self):
if self._address:
return self._address
@address.setter
def address(self, address):
if isinstance(address, basestring):
self._address = address
elif address is None:
self._address = None
else:
raise ValueError
@property
def phoneNumber(self):
if self._phoneNumber:
return self._phoneNumber
@phoneNumber.setter
def phoneNumber(self, phoneNumber):
if isinstance(phoneNumber, basestring):
self._phoneNumber = phoneNumber
elif phoneNumber is None:
self._phoneNumber = None
else:
raise ValueError
def etree_element(self):
element = super(_Feature, self).etree_element()
if self.name:
name = etree.SubElement(element, "%sname" % self.ns)
name.text = self.name
if self.description:
description = etree.SubElement(element, "%sdescription" % self.ns)
description.text = self.description
visibility = etree.SubElement(element, "%svisibility" % self.ns)
visibility.text = str(self.visibility)
if self.isopen:
isopen = etree.SubElement(element, "%sopen" % self.ns)
isopen.text = str(self.isopen)
if self._styleUrl is not None:
element.append(self._styleUrl.etree_element())
for style in self.styles():
element.append(style.etree_element())
if self.snippet:
snippet = etree.SubElement(element, "%sSnippet" % self.ns)
if isinstance(self.snippet, basestring):
snippet.text = self.snippet
else:
if not (isinstance(self.snippet['text'], basestring)):
raise TypeError("text snippet should be of"
"type basestring")
snippet.text = self.snippet['text']
if self.snippet.get('maxLines'):
snippet.set('maxLines', str(self.snippet['maxLines']))
if (self._time_span is not None) and (self._time_stamp is not None):
raise ValueError(
'Either Timestamp or Timespan can be defined, not both'
)
elif self._time_span is not None:
element.append(self._time_span.etree_element())
elif self._time_stamp is not None:
element.append(self._time_stamp.etree_element())
if self._atom_link is not None:
element.append(self._atom_link.etree_element())
if self._atom_author is not None:
element.append(self._atom_author.etree_element())
if self.extended_data is not None:
element.append(self.extended_data.etree_element())
if self._address is not None:
address = etree.SubElement(element, '%saddress' % self.ns)
address.text = self._address
if self._phoneNumber is not None:
phoneNumber = etree.SubElement(element, '%sphoneNumber' % self.ns)
phoneNumber.text = self._phoneNumber
return element
def from_element(self, element):
super(_Feature, self).from_element(element)
name = element.find('%sname' % self.ns)
if name is not None:
self.name = name.text
description = element.find('%sdescription' % self.ns)
if description is not None:
self.description = description.text
visibility = element.find('%svisibility' % self.ns)
if visibility is not None:
if visibility.text in ['1', 'true']:
self.visibility = 1
else:
self.visibility = 0
isopen = element.find('%sopen' % self.ns)
if isopen is not None:
if isopen.text in ['1', 'true']:
self.isopen = 1
else:
self.isopen = 0
styles = element.findall('%sStyle' % self.ns)
for style in styles:
s = Style(self.ns)
s.from_element(style)
self.append_style(s)
styles = element.findall('%sStyleMap' % self.ns)
for style in styles:
s = StyleMap(self.ns)
s.from_element(style)
self.append_style(s)
style_url = element.find('%sstyleUrl' % self.ns)
if style_url is not None:
s = StyleUrl(self.ns)
s.from_element(style_url)
self._styleUrl = s
snippet = element.find('%sSnippet' % self.ns)
if snippet is not None:
_snippet = {'text': snippet.text}
if snippet.get('maxLines'):
_snippet['maxLines'] = int(snippet.get('maxLines'))
self.snippet = _snippet
timespan = element.find('%sTimeSpan' % self.ns)
if timespan is not None:
s = TimeSpan(self.ns)
s.from_element(timespan)
self._time_span = s
timestamp = element.find('%sTimeStamp' % self.ns)
if timestamp is not None:
s = TimeStamp(self.ns)
s.from_element(timestamp)
self._time_stamp = s
atom_link = element.find('%slink' % atom.NS)
if atom_link is not None:
s = atom.Link()
s.from_element(atom_link)
self._atom_link = s
atom_author = element.find('%sauthor' % atom.NS)
if atom_author is not None:
s = atom.Author()
s.from_element(atom_author)
self._atom_author = s
extended_data = element.find('%sExtendedData' % self.ns)
if extended_data is not None:
x = ExtendedData(self.ns)
x.from_element(extended_data)
self.extended_data = x
# else:
# logger.warn(
# 'arbitrary or typed extended data is not yet supported'
# )
address = element.find('%saddress' % self.ns)
if address is not None:
self.address = address.text
phoneNumber = element.find('%sphoneNumber' % self.ns)
if phoneNumber is not None:
self.phoneNumber = phoneNumber.text
class _Container(_Feature):
"""
abstract element; do not create
A Container element holds one or more Features and allows the
creation of nested hierarchies.
subclasses are:
Document,
Folder
"""
_features = []
def __init__(
self, ns=None, id=None, name=None, description=None,
styles=None, styleUrl=None
):
super(_Container, self).__init__(
ns, id, name, description, styles, styleUrl
)
self._features = []
def features(self):
""" iterate over features """
for feature in self._features:
if isinstance(feature, (Folder, Placemark, Document)):
yield feature
else:
raise TypeError(
"Features must be instances of "
"(Folder, Placemark, Document)"
)
def etree_element(self):
element = super(_Container, self).etree_element()
for feature in self.features():
element.append(feature.etree_element())
return element
def append(self, kmlobj):
""" append a feature """
if isinstance(kmlobj, (Folder, Placemark, Document)):
self._features.append(kmlobj)
else:
raise TypeError(
"Features must be instances of "
"(Folder, Placemark, Document)"
)
if not (kmlobj != self):
raise AssertionError(" kml object should not be instance of class"
"(self)")
class _Overlay(_Feature):
"""
abstract element; do not create
Base type for image overlays drawn on the planet surface or on the screen
A Container element holds one or more Features and allows the creation of
nested hierarchies.
"""
_color = None
# Color values expressed in hexadecimal notation, including opacity (alpha)
# values. The order of expression is alphaOverlay, blue, green, red
# (AABBGGRR). The range of values for any one color is 0 to 255 (00 to ff).
# For opacity, 00 is fully transparent and ff is fully opaque.
_drawOrder = None
# Defines the stacking order for the images in overlapping overlays.
# Overlays with higher <drawOrder> values are drawn on top of those with
# lower <drawOrder> values.
_icon = None
# Defines the image associated with the overlay. Contains an <href> html
# tag which defines the location of the image to be used as the overlay.
# The location can be either on a local file system or on a webserver. If
# this element is omitted or contains no <href>, a rectangle is drawn using
# the color and size defined by the ground or screen overlay.
def __init__(
self, ns=None, id=None, name=None, description=None,
styles=None, styleUrl=None
):
super(_Overlay, self).__init__(
ns, id, name, description, styles, styleUrl
)
@property
def color(self):
return self._color
@color.setter
def color(self, color):
if isinstance(color, basestring):
self._color = color
elif color is None:
self._color = None
else:
raise ValueError
@property
def drawOrder(self):
return self._drawOrder
@drawOrder.setter
def drawOrder(self, value):
if isinstance(value, (basestring, int, float)):
self._drawOrder = str(value)
elif value is None:
self._drawOrder = None
else:
raise ValueError
@property
def icon(self):
return self._icon
@icon.setter
def icon(self, url):
if isinstance(url, basestring):
if not url.startswith('<href>'):
url = '<href>' + url
if not url.endswith('</href>'):
url = url + '</href>'
self._icon = url
elif url is None:
self._icon = None
else:
raise ValueError
def etree_element(self):
element = super(_Overlay, self).etree_element()
if self._color:
color = etree.SubElement(element, "%scolor" % self.ns)
color.text = self._color
if self._drawOrder:
drawOrder = etree.SubElement(element, "%sdrawOrder" % self.ns)
drawOrder.text = self._drawOrder
if self._icon:
icon = etree.SubElement(element, "%sicon" % self.ns)
icon.text = self._icon
return element
def from_element(self, element):
super(_Overlay, self).from_element(element)
color = element.find('%scolor' % self.ns)
if color is not None:
self.color = color.text
drawOrder = element.find('%sdrawOrder' % self.ns)
if drawOrder is not None:
self.drawOrder = drawOrder.text
icon = element.find('%sicon' % self.ns)
if icon is not None:
self.icon = icon.text
class GroundOverlay(_Overlay):
"""
This element draws an image overlay draped onto the terrain. The <href>
child of <Icon> specifies the image to be used as the overlay. This file
can be either on a local file system or on a web server. If this element is
omitted or contains no <href>, a rectangle is drawn using the color and
LatLonBox bounds defined by the ground overlay.
"""
__name__ = 'GroundOverlay'
_altitude = None
# Specifies the distance above the earth's surface, in meters, and is
# interpreted according to the altitude mode.
_altitudeMode = 'clampToGround'
# Specifies how the <altitude> is interpreted. Possible values are:
# clampToGround -
# (default) Indicates to ignore the altitude specification and drape
# the overlay over the terrain.
# absolute -
# Sets the altitude of the overlay relative to sea level, regardless
# of the actual elevation of the terrain beneath the element. For
# example, if you set the altitude of an overlay to 10 meters with an
# absolute altitude mode, the overlay will appear to be at ground
# level if the terrain beneath is also 10 meters above sea level. If
# the terrain is 3 meters above sea level, the overlay will appear
# elevated above the terrain by 7 meters.
# - LatLonBox -
# TODO: Convert this to it's own class?
# Specifies where the top, bottom, right, and left sides of a bounding box
# for the ground overlay are aligned. Also, optionally the rotation of the
# overlay.
_north = None
# Specifies the latitude of the north edge of the bounding box, in decimal
# degrees from 0 to ±90.
_south = None
# Specifies the latitude of the south edge of the bounding box, in decimal
# degrees from 0 to ±90.
_east = None
# Specifies the longitude of the east edge of the bounding box, in decimal
# degrees from 0 to ±180. (For overlays that overlap the meridian of 180°
# longitude, values can extend beyond that range.)
_west = None
# Specifies the longitude of the west edge of the bounding box, in decimal
# degrees from 0 to ±180. (For overlays that overlap the meridian of 180°
# longitude, values can extend beyond that range.)
_rotation = None
# Specifies a rotation of the overlay about its center, in degrees. Values
# can be ±180. The default is 0 (north). Rotations are specified in a
# counterclockwise direction.
# TODO: <gx:LatLonQuad>
# Used for nonrectangular quadrilateral ground overlays.
_latLonQuad = None
@property
def altitude(self):
return self._altitude
@altitude.setter
def altitude(self, value):
if isinstance(value, (basestring, int, float)):
self._altitude = str(value)
elif value is None:
self._altitude = None
else:
raise ValueError
@property
def altitudeMode(self):
return self._altitudeMode
@altitudeMode.setter
def altitudeMode(self, mode):
if mode in ('clampToGround', 'absolute'):
self._altitudeMode = str(mode)
else:
self._altitudeMode = 'clampToGround'
@property
def north(self):
return self._north
@north.setter
def north(self, value):
if isinstance(value, (basestring, int, float)):
self._north = str(value)
elif value is None:
self._north = None
else:
raise ValueError
@property
def south(self):
return self._south
@south.setter
def south(self, value):
if isinstance(value, (basestring, int, float)):
self._south = str(value)
elif value is None:
self._south = None
else:
raise ValueError
@property
def east(self):
return self._east
@east.setter
def east(self, value):
if isinstance(value, (basestring, int, float)):
self._east = str(value)
elif value is None:
self._east = None
else:
raise ValueError
@property
def west(self):
return self._west
@west.setter
def west(self, value):
if isinstance(value, (basestring, int, float)):
self._west = str(value)
elif value is None:
self._west = None
else:
raise ValueError
@property
def rotation(self):
return self._rotation
@rotation.setter
def rotation(self, value):
if isinstance(value, (basestring, int, float)):
self._rotation = str(value)
elif value is None:
self._rotation = None
else:
raise ValueError
def latLonBox(self, north, south, east, west, rotation=0):
# TODO: Check for bounds (0:+/-90 or 0:+/-180 degrees)
self.north = north
self.south = south
self.east = east
self.west = west
self.rotation = rotation
def etree_element(self):
element = super(GroundOverlay, self).etree_element()
if self._altitude:
altitude = etree.SubElement(element, "%saltitude" % self.ns)
altitude.text = self._altitude
if self._altitudeMode:
altitudeMode = etree.SubElement(
element, "%saltitudeMode" % self.ns
)
altitudeMode.text = self._altitudeMode
if all([self._north, self._south, self._east, self._west]):
latLonBox = etree.SubElement(element, '%slatLonBox' % self.ns)
north = etree.SubElement(latLonBox, '%snorth' % self.ns)
north.text = self._north
south = etree.SubElement(latLonBox, '%ssouth' % self.ns)
south.text = self._south
east = etree.SubElement(latLonBox, '%seast' % self.ns)
east.text = self._east
west = etree.SubElement(latLonBox, '%swest' % self.ns)
west.text = self._west
if self._rotation:
rotation = etree.SubElement(latLonBox, '%srotation' % self.ns)
rotation.text = self._rotation
return element
def from_element(self, element):
super(GroundOverlay, self).from_element(element)
altitude = element.find('%saltitude' % self.ns)
if altitude is not None:
self.altitude = altitude.text
altitudeMode = element.find('%saltitudeMode' % self.ns)
if altitudeMode is not None:
self.altitudeMode = altitudeMode.text
latLonBox = element.find('%slatLonBox' % self.ns)
if latLonBox is not None:
north = latLonBox.find('%snorth' % self.ns)
if north is not None:
self.north = north.text
south = latLonBox.find('%ssouth' % self.ns)
if south is not None:
self.south = south.text
east = latLonBox.find('%seast' % self.ns)
if east is not None:
self.east = east.text
west = latLonBox.find('%swest' % self.ns)
if west is not None:
self.west = west.text
rotation = latLonBox.find('%srotation' % self.ns)
if rotation is not None:
self.rotation = rotation.text
class Document(_Container):
"""
A Document is a container for features and styles. This element is
required if your KML file uses shared styles or schemata for typed
extended data
"""
__name__ = "Document"
_schemata = None
def schemata(self):
if self._schemata:
for schema in self._schemata:
yield schema
def append_schema(self, schema):
if self._schemata is None:
self._schemata = []
if isinstance(schema, Schema):
self._schemata.append(schema)
else:
s = Schema(schema)
self._schemata.append(s)
def from_element(self, element):
super(Document, self).from_element(element)
folders = element.findall('%sFolder' % self.ns)
for folder in folders:
feature = Folder(self.ns)
feature.from_element(folder)
self.append(feature)
placemarks = element.findall('%sPlacemark' % self.ns)
for placemark in placemarks: