cleder / fastkml Goto Github PK
View Code? Open in Web Editor NEWFast ๐๏ธ KML processing for python
Home Page: https://fastkml.readthedocs.io
Fast ๐๏ธ KML processing for python
Home Page: https://fastkml.readthedocs.io
The current documentation about reading a file offers almost no information about how to read different parts of a KML file. Likewise, the reference guide gives no information about what to do with Placemarks.
For instance, this is the file I am trying to parse. Based on the quick tutorial, I can get the Placemark, but I can't do anything with it and all the attributes are set to None.
<?xml version="1.0" encoding="UTF-8"?><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"><Document><name>2016-07-17T11:19:39Z</name>
<Placemark>
<gx:Track>
<when>2016-07-17T11:19:39Z</when>
<gx:coord>13.4410151 52.5321779 0.0</gx:coord>
<when>2016-07-17T11:20:48Z</when>
<gx:coord>13.4445348 52.52911408 66.0</gx:coord>
<when>2016-07-17T11:20:54Z</when>
<gx:coord>13.444335 52.5292497 0.0</gx:coord>
<when>2016-07-17T11:21:10Z</when>
<gx:coord>13.4443962 52.5291495 0.0</gx:coord>
I've read the documentation, but I'm still unclear one how one can create an element for which there is no predefined function. For instance, can you provide a quick example of how one might implement the or element?
I am trying to adjust the line style for a LineString. The code is below. I get an error: "TypeError: 'LineStyle' object is not iterable.
k = kml.KML()
ns = '{http://www.opengis.net/kml/2.2}'
# Create a KML Document and add it to the KML root object
d = kml.Document(ns, 'docid', 'Sherwood', 'Sherwood data')
k.append(d)
# Create a Placemark with a simple polygon geometry and add it to the
# second folder of the Document
f = kml.Folder(ns, 'fid', 'f name', 'f description')
d.append(f)
ls = LineStyle(ns, color='red', width=3)
p = kml.Placemark(ns, 'id', 'Flight path', styles=ls)
p.geometry = LineString(list(longlat))
f.append(p)
Seriously nice work! Great documentation and library has a good api and easy to work with.
I'm getting an install error trying to install this into Python 3.4
Downloading/unpacking git+https://github.com/cleder/fastkml.git
Cloning https://github.com/cleder/fastkml.git to /tmp/pip-n5xr_10y-build
Running setup.py (path:/tmp/pip-n5xr_10y-build/setup.py) egg_info for package from git+https://github.com/cleder/fastkml.git
Traceback (most recent call last):
File "<string>", line 17, in <module>
File "/tmp/pip-n5xr_10y-build/setup.py", line 24, in <module>
open(os.path.join("docs", "HISTORY.txt")).read() + "\n" +
File "/usr/lib/python3.4/encodings/ascii.py", line 26, in decode
return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 6630: ordinal not in range(128)
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "<string>", line 17, in <module>
File "/tmp/pip-n5xr_10y-build/setup.py", line 24, in <module>
open(os.path.join("docs", "HISTORY.txt")).read() + "\n" +
File "/usr/lib/python3.4/encodings/ascii.py", line 26, in decode
return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 6630: ordinal not in range(128)
ArcGIS Explorer fails to read fastkml generated files.
Setting the kml namespace to be a default one fixes it for me
diff --git a/fastkml/kml.py b/fastkml/kml.py
index 756b4bd..677e840 100644
--- a/fastkml/kml.py
+++ b/fastkml/kml.py
@@ -100,7 +100,7 @@ class KML(object):
raise TypeError
def etree_element(self):
- root = etree.Element('%skml' % self.ns)
+ root = etree.Element('%skml' % self.ns, nsmap={None: self.ns[1:-1]})
for feature in self.features():
root.append(feature.etree_element())
return root
Also it makes the generated kml smaller.
import fastkml
fastkml.__version__
'0.11'
File "/usr/local/lib/python2.7/dist-packages/fastkml/kml.py", line 101, in from_string
feature.from_element(document)
File "/usr/local/lib/python2.7/dist-packages/fastkml/kml.py", line 991, in from_element
feature.from_element(folder)
File "/usr/local/lib/python2.7/dist-packages/fastkml/kml.py", line 1030, in from_element
feature.from_element(folder)
File "/usr/local/lib/python2.7/dist-packages/fastkml/kml.py", line 1035, in from_element
feature.from_element(placemark)
File "/usr/local/lib/python2.7/dist-packages/fastkml/kml.py", line 1077, in from_element
geom.from_element(line)
File "/usr/local/lib/python2.7/dist-packages/fastkml/geometry.py", line 413, in from_element
geom = self._get_geometry(element)
File "/usr/local/lib/python2.7/dist-packages/fastkml/geometry.py", line 347, in _get_geometry
return LineString(coords)
File "/usr/local/lib/python2.7/dist-packages/shapely/geometry/linestring.py", line 48, in __init__
self._set_coords(coordinates)
File "/usr/local/lib/python2.7/dist-packages/shapely/geometry/linestring.py", line 97, in _set_coords
ret = geos_linestring_from_py(coordinates)
File "shapely/speedups/_speedups.pyx", line 152, in shapely.speedups._speedups.geos_linestring_from_py
ValueError: LineStrings must have at least 2 coordinate tuples
Hello fastkml developers,
I'm on Python 2.7 and trying to import kml into my shell. Unfortunately, I am getting the message below
from fastkml import kml
No handlers could be found for logger "fastkml.config"
I see that some parts of the build https://travis-ci.org/cleder/fastkml/jobs/220557807 are failing for this reason as well.
Edit: I should clarify that I was still able to import kml into my namespace - so this is not a bug. Could the maintainers kindly close this issue. Many thanks!
"It provides a subset of KML and is aimed at documents that can be read from multiple clients such as openlayers and google maps rather than to give you all functionality that KML on google earth provides."
what is missing for the full google earth experience is the gx extensions
fastkml doesn't support gx:Track
geometries.
what happens is that kml.py / Placemark / from_element method cannot detect a {http://www.google.com/kml/ext/2.2}Track
element, thus arrives at No geometries found
error.
sample file (saved with latest Google Earth):
https://gist.github.com/hyperknot/32ac836881b760aa3d02cc24d01a7dfd
Hi there. With Python 3.7.6, Django 2.2.5, fastkml 0.11, I have an app that attempts to import fastkml in the view.py and this is raising an error. Oddly, the error does not occur on import into the Python console. For example:
Python 3.7.6 (default, Dec 30 2019, 19:38:26)
[Clang 11.0.0 (clang-1100.0.33.16)] on darwin
Django 2.2.5
import fastkml
No problem. But when I attempt to call it in my views.py I get error. The traceback looks like this:
Exception in thread django-main-thread:
Traceback (most recent call last):
File "/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 926, in _bootstrap_inner
self.run()
File "/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "/Users/dreed/Documents/pycharm/paleocore/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper
fn(*args, **kwargs)
File "/Users/dreed/Documents/pycharm/paleocore/venv/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run
autoreload.raise_last_exception()
File "/Users/dreed/Documents/pycharm/paleocore/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 77, in raise_last_exception
raise _exception[1]
File "/Users/dreed/Documents/pycharm/paleocore/venv/lib/python3.7/site-packages/django/core/management/init.py", line 337, in execute
autoreload.check_errors(django.setup)()
File "/Users/dreed/Documents/pycharm/paleocore/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper
fn(*args, **kwargs)
File "/Users/dreed/Documents/pycharm/paleocore/venv/lib/python3.7/site-packages/django/init.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "/Users/dreed/Documents/pycharm/paleocore/venv/lib/python3.7/site-packages/django/apps/registry.py", line 122, in populate
app_config.ready()
File "/Users/dreed/Documents/pycharm/paleocore/venv/lib/python3.7/site-packages/django/contrib/admin/apps.py", line 24, in ready
self.module.autodiscover()
File "/Users/dreed/Documents/pycharm/paleocore/venv/lib/python3.7/site-packages/django/contrib/admin/init.py", line 26, in autodiscover
autodiscover_modules('admin', register_to=site)
File "/Users/dreed/Documents/pycharm/paleocore/venv/lib/python3.7/site-packages/django/utils/module_loading.py", line 47, in autodiscover_modules
import_module('%s.%s' % (app_config.name, module_to_search))
File "/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/init.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "", line 1006, in _gcd_import
File "", line 983, in _find_and_load
File "", line 967, in _find_and_load_unlocked
File "", line 677, in _load_unlocked
File "", line 728, in exec_module
File "", line 219, in _call_with_frames_removed
File "/Users/dreed/Documents/pycharm/paleocore/mlp/admin.py", line 10, in
import mlp.views # This line raises exception!
File "/Users/dreed/Documents/pycharm/paleocore/mlp/views.py", line 3, in
from fastkml import kml, Placemark, Folder, Document
File "/Users/dreed/Documents/pycharm/paleocore/venv/lib/python3.7/site-packages/fastkml/init.py", line 28, in
from pkg_resources import get_distribution, DistributionNotFound
File "/Users/dreed/Documents/pycharm/paleocore/venv/lib/python3.7/site-packages/pkg_resources/init.py", line 3250, in
@_call_aside
File "/Users/dreed/Documents/pycharm/paleocore/venv/lib/python3.7/site-packages/pkg_resources/init.py", line 3234, in _call_aside
f(*args, **kwargs)
File "/Users/dreed/Documents/pycharm/paleocore/venv/lib/python3.7/site-packages/pkg_resources/init.py", line 3263, in _initialize_master_working_set
working_set = WorkingSet._build_master()
File "/Users/dreed/Documents/pycharm/paleocore/venv/lib/python3.7/site-packages/pkg_resources/init.py", line 574, in _build_master
ws = cls()
File "/Users/dreed/Documents/pycharm/paleocore/venv/lib/python3.7/site-packages/pkg_resources/init.py", line 567, in init
self.add_entry(entry)
File "/Users/dreed/Documents/pycharm/paleocore/venv/lib/python3.7/site-packages/pkg_resources/init.py", line 621, in add_entry
self.entry_keys.setdefault(entry, [])
TypeError: unhashable type: 'Path'
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://earth.google.com/kml/2.2">
<Document>
<name>SPEED-NORAIN_RAPIDSCAT_999_201504042251_201504050024</name>
<open>0</open>
<GroundOverlay>
<Icon>
<href>SPEED-NORAIN_RAPIDSCAT_999_201504042251_201504050024.png</href>
</Icon>
<LatLonBox>
<north>60.0</north><south>-60.0</south><east>179</east><west>-180</west>
</LatLonBox>
</GroundOverlay>
</Document>
</kml>
Hello,
I noticed in CI builds https://travis-ci.org/cleder/fastkml/builds that tests for Python 3.4 are not passing anymore.
Maybe you should consider dropping py34 support.
Kind regards
First I want to say thank you for sharing fastkml. It's been very useful to me, and I appreciate your work.
Recently, I needed to make a KML file with arbitrary XML in the ExtendedData of Placemark objects, and I found that this feature is not supported. I put in a simple hack to make it work, which was to make an ExtendedData object by passing in a pre-constructed etree and storing it in the object, then having from_element return the ExtendedData element with the provided etree as a child. I'd like to add this feature using a nicer implementation, though. I suppose the thing to do would be to add a TypedData class and pass TypedData elements into a TypedExtendedData object?
I used fastkml for a project which relied on it quite extensively. I chose not to install shapely, because it had more dependencies than pygeoif. I later included another module to my project, which also needed shapely, so I decided to install it anyways. However, quite a few issues arose when trying shapely instead of pygeoif, which I didn't really see coming. For example, a LineString of length 1 throws an error in Shapely, but doesn't in pygeoif. There are more examples, but that's not really relevant.
I guess their behavior and implementation is a bit different, and can't be converted 1 on 1.
I worked around it by changing the fastkml module code from:
try:
from shapely.geometry import Point, LineString, Polygon
from shapely.geometry import MultiPoint, MultiLineString, MultiPolygon
....
except ImportError:
from pygeoif.geometry import Point, LineString, Polygon
from pygeoif.geometry import MultiPoint, MultiLineString, MultiPolygon
....
to:
from pygeoif.geometry import Point, LineString, Polygon
from pygeoif.geometry import MultiPoint, MultiLineString, MultiPolygon
....
But it's obviously not ideal. It would be nice to be able to specify whatever geometry module fastkml is using, when either initing a KML instance or when importing the module into your project, to make project depending on this module more portable. E.g:
from fastkml import kml
kml.use('pygeoif')
FastKML reads KML snippets from strings rather than files. Reading files using Pythons standard document parser makes assumptions about encoding and it the UTF / Unicode encoding string is forwarded to lxml it does not want to parse it and wants to perform its own interpretation or obtain the data as raw bytes. It would be good to extend fastKML to include a from_file method in the parser to circumvent this and pass the file directly to lxml for encoding interpretation etc.
k = kml.KML()
with open(track_KML, 'r') as myfile:
data=myfile.read().replace('\n', '')
k.from_string(data)
ValueError Traceback (most recent call last)
in ()
2 with open(track_KML, 'r') as myfile:
3 data=myfile.read().replace('\n', '')
----> 4 k.from_string(data)c:\python35\lib\site-packages\fastkml\kml.py in from_string(self, xml_string)
89 element = etree.fromstring(
90 xml_string,
---> 91 parser=etree.XMLParser(huge_tree=True)
92 )
93 else:src\lxml\lxml.etree.pyx in lxml.etree.fromstring (src\lxml\lxml.etree.c:79593)()
src\lxml\parser.pxi in lxml.etree._parseMemoryDocument (src\lxml\lxml.etree.c:119053)()
ValueError: Unicode strings with encoding declaration are not supported. Please use bytes input or XML fragments without declaration.
The error is indicative of encoding conflicts and direct parsing from files will be really useful for my use-cases.
I have problems creating documents, following the code snippets in the example. I have geometries from Shapely I need to visualise for debugging, and thought KML to Google Earth as a good choice for this.
Traceback (most recent call last):
File "./gpxtest.py", line 459, in <module>
country = test_relation(testing)
File "./gpxtest.py", line 243, in test_relation
mk_kml(test, id, name)
File "./gpxtest.py", line 265, in mk_kml
d = klm.Document(ns, str(id), name, 'Border visualisation')
AttributeError: 'KML' object has no attribute 'Document'
Suspect I will get the same errors for Folder
and geometry
Code block in question:
def mk_kml(object, id, name):
print "Creating KML"
try:
klm = kml.KML()
ns = '{http://www.opengis.net/kml/2.2}'
d = klm.Document(ns, str(id), name, 'Border visualization')
klm.append(d)
f1 = klm.Folder(ns, str(id), 'Boundaries', 'Border visualization')
d.append(f1)
p = klm.Placemark(ns, str(id), name, 'Border of {0}'.format(name))
p.geometry = object
f1.append(p)
filename = "./klm/"+id+"_"+name.replace(" ", "_")+".kml"
fil = open(filename, 'w')
fil.write(klm.to_string(prettyprint=True))
fil.close()
print "KML Saved"
except:
print "Failed to create KML"
raise
Hi there, when i use fastkml in Python 3 to parse this sample KML file from Google, i get the warning WARNING:fastkml.kml:No geometries found
. What's going on here?
The example on the README.md is misleading, because "features" is now a generator and as such you can't do any of this:
>>> len(k.features())
1
>>> len(k.features()[0].features())
2
I'm not sure why you changed it - it may be more elegant, and provides a little more safety by hiding the _features array. However it makes it less convenient to access the first element, which is a pretty common case if you're actually parsing a single document.
python setup.py install
Traceback (most recent call last):
File "setup.py", line 6, in <module>
import fastkml
File "/home/..../src/fastkml/fastkml/__init__.py", line 27, in <module>
from .config import __version__
ImportError: cannot import name __version__
e.g. (103.7940492, 1.4391202)
-> 103.794049,1.439120
In geometry.py
, _etree_coordinates(self, coordinates)
is casting coordinates to %f
, reducing the values to 6 decimal places.
I have a KML looking like the following:
<?xml version="1.0" encoding="UTF-8"?><kml xmlns="http://www.opengis.net/kml/2.2">
<Folder>
<Placemark>
<name/>
<description/>
<Polygon>
<outerBoundaryIs>
<LinearRing>
<coordinates></coordinates>
</LinearRing>
</outerBoundaryIs>
</Polygon>
</Placemark>
</Folder>
</kml>
I know this is stupid but I was sent one looking like that by a customer and it's parsed with no exception in OpenLayers.
It however raises an error in faskml.
Can something be done to handle geometries with empty coordinates or at least prevent the code from failing?
When parsing e.g. https://developers.google.com/kml/documentation/us_states.kml, there is a bug because you do not allow a MultiGeometry (which you consider a Geometry) to contain another MultiGeometry. The nested MultiGeometry in the US state placeholders of above .kml file are thus ignored.
Easy to fix I suspect by adding element.findall('%sMultiGeometry' % self.ns)
line in the _get_multigeometry
method.
I have a KML file which has been exported from another system which translates all of the meta data about each point into the <ExtendedData>
tag. This information can be accessed but the schemaurl
remains inaccessible through this package.
In this case, it is necessary to know what the whole entire extended schema is to be sure to structure data retrieval/extraction properly.
<ExtendedData>
<SchemaData schemaUrl="#kml_schema_ft_obj">
<SimpleData name="id">1234</SimpleData>
<SimpleData name="total_well_depth">2468</SimpleData>
<SimpleData name="owner">SEIFERT</SimpleData>
</SchemaData>
</ExtendedData>
In the case above, I need to access all of the elements of the schema where the id
is kml_schema_ft_obj
.
from fastkml import kml
from shapely.geometry import Point, LineString, Polygon
k = kml.KML()
ns = '{http://www.opengis.net/kml/2.2}'
##Create a MKL Document and add it to the KML root object
d = kml.Document(ns, 'ID', 'BIM_path', 'Suwannee_office')
k.append(d)
f1 = kml.Folder(ns, 'fid', 'Trajectory', 'f_description')
d.append(f1)
p = kml.Geometry.geometry(ns, id='id', altitude_mode='relativeToGround')
p.geometry = LineString([(-84.038347, 33.999304, 100), (-84.038347, 33.999304, 100),
(-84.037679, 33.999255, 100), (-84.037678, 33.999254, 100)])
f1.append(p)
On the attached file, fastkml throws a warning message: 'No geometries found' from Placemark / from_element.
At the moment, there is no way to detect this error scenario, so a gpsbabel cleaning could run. It'd be important to raise an error and not just log a warning in such case.
The KML timespan and timestamp features are not documented. After a light browsing of the sourcecode, it's not clear that there is support for adding a timestamp to a KML document. It would be nice to make it clear if this is supported, and if it is, to provide a simple example showing how to use it
If the basic docs are used as a reference, then adding the bit around t
will create the appropriate timestamp.
# Create a Placemark with a simple polygon geometry and add it to the Document
p = kml.Placemark(ns, 'id', 'name (poly)', 'description (poly)')
p.geometry = Point([(0, 0)])
d.append(p)
t = kml.TimeStamp()
t.timestamp, dummy = t.parse_str('1997-07-16T07:30:15Z')
p.timeStamp = t.timestamp
P.S. Awesome lib, thanks for creating it!
Hello,
I would like to get the coordinates of a Polygon element in a KML file.
I can get the name of the Placemark but not the Polygon, etc.
<?xml version="1.0" encoding="UTF-8"?>
<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">
<Document>
<name>Polygone_Site.kmz</name>
<Style id="s_ylw-pushpin">
<IconStyle>
<scale>1.1</scale>
<Icon>
<href>http://maps.google.com/mapfiles/kml/pushpin/ylw-pushpin.png</href>
</Icon>
<hotSpot x="20" y="2" xunits="pixels" yunits="pixels"/>
</IconStyle>
</Style>
<StyleMap id="m_ylw-pushpin">
<Pair>
<key>normal</key>
<styleUrl>#s_ylw-pushpin</styleUrl>
</Pair>
<Pair>
<key>highlight</key>
<styleUrl>#s_ylw-pushpin_hl</styleUrl>
</Pair>
</StyleMap>
<Style id="s_ylw-pushpin_hl">
<IconStyle>
<scale>1.3</scale>
<Icon>
<href>http://maps.google.com/mapfiles/kml/pushpin/ylw-pushpin.png</href>
</Icon>
<hotSpot x="20" y="2" xunits="pixels" yunits="pixels"/>
</IconStyle>
</Style>
<Placemark>
<name>Polygone_Site</name>
<styleUrl>#m_ylw-pushpin</styleUrl>
<Polygon>
<tessellate>1</tessellate>
<outerBoundaryIs>
<LinearRing>
<coordinates>
4.914362494420819,45.64823247608015,0 4.917841606174669,45.649117478459,0 4.919216692316262,45.65112174068214,0 4.92163044974935,45.65877214704558,0 4.918801692845934,45.6588311402833,0 4.918325644559123,45.65572052537501,0 4.914276424819033,45.65550842377992,0 4.914362494420819,45.64823247608015,0
</coordinates>
</LinearRing>
</outerBoundaryIs>
</Polygon>
</Placemark>
</Document>
</kml>
with open("doc.kml", "rt") as fichier:
doc = fichier.read().encode("utf-8")
k = kml.KML()
k.from_string(doc)
features = list(k.features())
f1 = list(features[0].features())
name = f1[0].name
Can you help me ? and tell me how to do that ?
Thanks !
I am looking for a way to create a shapely polygon from existing KML files, my script is currently getting geographical information for comparison from Overpass
, and stores the polygons as KML as well as running the comparison. Since some of the polygons are huge, it takes hours creating all the polygons. If the script could load reoccurring polygons from the stored KML files I would have a huge speed increase in the script, and be able to compare much more data. I would like to, if possible, avoid need for converting the KML's with external software (ogr2ogr
conversion to .wkb
for example) as relying on external executions like that are likely to interrupt the automated workflow.
"Features and geometry associated with a Region are drawn only when the Region is active."
https://developers.google.com/kml/documentation/kmlreference#region
Hi, I am Aryan, a GSoC 2020 student with Mission Support System of Python Software Foundation.
Over the last 3 months, I used the Fastkml library to enhance KML support in a feature of MSS. I was really pleased with how easy it was to use Fastkml to parse geometries and styles :))
Keeping up with the Open Source spirit, I would like to give back to Fastkml by contributing to it.
During my GSoC period, I had done a Bandit run of the Fastkml project. Bandit is a tool designed to find common security issues in Python code. It had thrown up the following error :
Error B101 ; assert_used --> "Use of assert detected. The enclosed code will be removed when compiling to optimised byte code."
Hello,
I don't know enough about XML and FastKML yet to solve this, even after reading through the docs on the site and Stackoverflow.
I need to 1) read a KML file, 2) Loop through each Placemark block, 3) Check if it contains a LineString, 4) If it does, add a new element to the block, and 5) save the whole thing into a new KML file.
Apparently, CSS/XPath is more readable than using tables with features.
Would someone have some working code I could use to get started?
Thank you.
#1. Read KML file
#2. Loop through Placemark
#3. If contains <LineString>, add <some>element</some> to current Placemark
#4. Save to new KML file
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>
<name>My Document</name>
<Placemark>
<name>My Waypoint</name>
<Point>
<coordinates>-122.371,37.816,0</coordinates>
</Point>
</Placemark>
<Placemark>
<name>My Track</name>
<LineString><coordinates>-0.376291,43.296237,199.75 -0.376299,43.296237,199.75</LineString>
</Placemark>
</Document>
</kml>
Ground overlays are a useful and standard feature of KML:
https://developers.google.com/kml/documentation/kml_tut#ground_overlays
Might be nice to support them in fastkml.
Even if value is mandatory, it happen's that value tag is missing in a Data tag.
Exemple:
<Placemark>
<name>Ligne Analytics</name>
<styleUrl>#msn_ylw-pushpin10</styleUrl>
<ExtendedData>
<Data name="title"/>
<Data name="description"/>
<Data name="stroke">
<value>#a3e46b</value>
</Data>
<Data name="stroke-width">
<value>8</value>
</Data>
<Data name="stroke-opacity">
<value>1</value>
</Data>
</ExtendedData>
<LineString>
<coordinates>x,y</coordinates>
</LineString>
</Placemark>
Problem's here:
https://github.com/cleder/fastkml/blob/master/fastkml/kml.py#L1441
self.value = element.find('%svalue' % self.ns).text
find() returns null, then null.text rise an AttributeError
File .../lib/python2.7/site-packages/fastkml/kml.py", line 1441, in from_element
self.value = element.find('%svalue' % self.ns).text
AttributeError: 'NoneType' object has no attribute 'text'
Taken from: https://github.com/cleder/fastkml/blob/0.9/docs/TODO.txt
Implement based on: https://developers.google.com/kml/documentation/extendeddata#opaquedata
Reading a kml file fails when there is an empty polygon present, meaning a valid kml file cannot be parsed.
I'm not sure if this issue belongs here or in pygeoif
though.
"example.kml"
<?xml version="1.0" encoding="UTF-8"?>
<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">
<Document>
<name>Google Earth My Places, 20200513 1020.kmz</name>
<Folder>
<Placemark>
<name>Untitled Polygon</name>
<styleUrl>#m_ylw-pushpin3</styleUrl>
<Polygon>
<tessellate>1</tessellate>
<outerBoundaryIs>
<LinearRing>
<coordinates>
</coordinates>
</LinearRing>
</outerBoundaryIs>
</Polygon>
</Placemark>
</Folder>
</Document>
</kml>
"mre.py"
if __name__ == "__main__":
with open("example.kml", "rb") as f:
doc = f.read()
k = kml.KML()
k.from_string(doc)
Traceback:
File "C:\Users\jamie\PycharmProjects\synergt\mre.py", line 17, in open_kml
k.from_string(doc)
File "C:\Users\jamie\Miniconda3\envs\synergt\lib\site-packages\fastkml\kml.py", line 101, in from_string
feature.from_element(document)
File "C:\Users\jamie\Miniconda3\envs\synergt\lib\site-packages\fastkml\kml.py", line 991, in from_element
feature.from_element(folder)
File "C:\Users\jamie\Miniconda3\envs\synergt\lib\site-packages\fastkml\kml.py", line 1035, in from_element
feature.from_element(placemark)
File "C:\Users\jamie\Miniconda3\envs\synergt\lib\site-packages\fastkml\kml.py", line 1083, in from_element
geom.from_element(polygon)
File "C:\Users\jamie\Miniconda3\envs\synergt\lib\site-packages\fastkml\geometry.py", line 413, in from_element
geom = self._get_geometry(element)
File "C:\Users\jamie\Miniconda3\envs\synergt\lib\site-packages\fastkml\geometry.py", line 351, in _get_geometry
ob = self._get_linear_ring(outer_boundary)
File "C:\Users\jamie\Miniconda3\envs\synergt\lib\site-packages\fastkml\geometry.py", line 335, in _get_linear_ring
return LinearRing(coords)
File "C:\Users\jamie\Miniconda3\envs\synergt\lib\site-packages\pygeoif\geometry.py", line 400, in __init__
if self._geoms[0].coords != self._geoms[-1].coords:
IndexError: list index out of range
I'm trying to use fastkml to parse some KML files given to me, these render fine in GoogleEarth but return an empty list when I parse with fastkml.
I had a look inside the non-working KML file and in the source kml.py and it seems that because the element inside the root kml element is a GroundOverlay the content is ignored.
Redacted example:
<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">
<GroundOverlay>
<name>blah</name>
<description>blah</description>
<gx:balloonVisibility>1</gx:balloonVisibility>
<Icon>
<href>some_file.png</href>
<viewBoundScale>0.75</viewBoundScale>
</Icon>
<LatLonBox>
<north>1</north>
<south>1</south>
<east>1</east>
<west>1</west>
</LatLonBox>
</GroundOverlay>
</kml>
Hi there,
The normal
and highlight
keyword args to StyleMap
's init method are ignored -- see here: https://github.com/cleder/fastkml/blob/master/fastkml/styles.py#L147
It looks like the only way to create one of these right now is to subclass StyleMap
?
I'm not sure what the intended usage is, but it seems like either A) a fix or B) a documentation update (and removal of those kwargs) is in order.
Let me know if I can help.
Thanks!
Colin
I'm new to fastkml, and I'm using it for parsing kml files. I've read through docs, and you guys has provided well-explained docs for setters. However, after reading through more docs and source code, I didn't find getters explicitly, so my parsing seems very handy and uncomfortable. In fact, in one of the example, you used getattr
as well. So, I'm requesting adding some explicit getters. So when people are parsing huge kmls, they will feel less uncomfortable.
Hi,
I am enabling ppc64le build on travis-ci. But its failing on amd64 itself with below error:
" Complete output from command python setup.py egg_info:
This lxml version requires Python 2.7, 3.5 or later.
----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-install-cdxqgk_6/lxml/
The command "if $LXML == true; then pip install lxml; fi" failed and exited with 1 during .
Your build has been stopped."
The full log can be tracked here: https://travis-ci.com/github/sanjaymsh/fastkml/builds/188579445
In my case , i have added both of the arch(amd64 & ppc64le), so its failing on both of the arch for python:3.4 with "LXML=true".
Please have look on this.
Thanks !!
Not sure if this is specific to my system, but the KML files written cannot be read by other viewers without further modification:
lxml
)Tested on http://kmlviewer.nsspot.net/
Produce updated documentation for FastKML including more usage examples.
Should be produced with Sphinx and be hosted on Read The Docs (http://read-the-docs.readthedocs.org/en/latest/getting_started.html)
Shapely checks on the geometry data passed to construct a Shapely.Geometry object.
And throws ValueError when LineString len(coordinates) less then 2.
But the error message contains no info from KML file, that's hard to find the error in the file.
Hi,
I have encountered problems parsing unix timestamp.
The library uses the entire timestamp values as year and as result I obtain a
ValueError: year is out of range
in my case the problem occurs with parameters like:
<TimeStamp><when>1483258435</when></TimeStamp>
Luca
Hello,
I'm new to fastkml and was quite surprised to see its API usage.
>>> from fastkml import kml
# Setup the string which contains the KML file we want to read
>>> doc = """<?xml version="1.0" encoding="UTF-8"?>
... <kml xmlns="http://www.opengis.net/kml/2.2">
... <Document>
... <name>Document.kml</name>
... <open>1</open>
... <Style id="exampleStyleDocument">
... <LabelStyle>
... <color>ff0000cc</color>
... </LabelStyle>
... </Style>
... <Placemark>
... <name>Document Feature 1</name>
... <styleUrl>#exampleStyleDocument</styleUrl>
... <Point>
... <coordinates>-122.371,37.816,0</coordinates>
... </Point>
... </Placemark>
... <Placemark>
... <name>Document Feature 2</name>
... <styleUrl>#exampleStyleDocument</styleUrl>
... <Point>
... <coordinates>-122.370,37.817,0</coordinates>
... </Point>
... </Placemark>
... </Document>
... </kml>"""
# Create the KML object to store the parsed result
>>> k = kml.KML()
# Read in the KML string
>>> k.from_string(doc)
why not using a static method instead
So it will be possible to simply do
k = kml.KML.from_string(doc)
using such API, it would make it possible open file
k = kml.KML.read_kml_file(filename)
using a simpler approach.
What is your opinion?
Kind regards
No handlers could be found for logger "fastkml.config" Traceback (most recent call last): File "/private/var/mobile/Containers/Shared/AppGroup/AA78F2EC-3EE8-40F4-A318-8A9AB1BCB5FF/Pythonista3/Documents/ceid-fixer/fkml.py", line 8, in <module> k.from_string(doc) File "/private/var/mobile/Containers/Shared/AppGroup/AA78F2EC-3EE8-40F4-A318-8A9AB1BCB5FF/Pythonista3/Documents/site-packages/fastkml/kml.py", line 101, in from_string feature.from_element(document) File "/private/var/mobile/Containers/Shared/AppGroup/AA78F2EC-3EE8-40F4-A318-8A9AB1BCB5FF/Pythonista3/Documents/site-packages/fastkml/kml.py", line 1001, in from_element s.from_element(schema) File "/private/var/mobile/Containers/Shared/AppGroup/AA78F2EC-3EE8-40F4-A318-8A9AB1BCB5FF/Pythonista3/Documents/site-packages/fastkml/kml.py", line 1359, in from_element self.append(sftype, sfname, sfdisplay_name) File "/private/var/mobile/Containers/Shared/AppGroup/AA78F2EC-3EE8-40F4-A318-8A9AB1BCB5FF/Pythonista3/Documents/site-packages/fastkml/kml.py", line 1337, in append "type must be one of ""'string', 'int', 'uint', 'short', " TypeError: type must be one of 'string', 'int', 'uint', 'short', 'ushort', 'float', 'double', 'bool'
The following code snippet gives an error:
TypeError: super(type, obj): obj must be an instance or subtype of type
from fastkml import kml
# initialize
k = kml.KML()
# import kml file
kml_filepath = r"G:\Projects\USA_West\Desert_Harvest\05_GIS\053_Data\kmz\fence_DH_20180810.kml"
with open(kml_filepath, 'rt', encoding="utf-8") as myfile:
kml_file=myfile.read()
k.from_string(kml_file)
I am not sure how to proceed from here. Please let me know if you need any other information from me.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.