My goal is to iterate over features in a given KML file and save each feature as a seperate KML file. I'm using python and it seems that ogr module can do it but I can't figure out how.
I am able to read a KML file into <class 'osgeo.ogr.DataSource'>
and <class 'osgeo.ogr.Layer'>
simply using:
import ogr
fn = r'C:\Users\kml folder\terre.kml'
driver = ogr.GetDriverByName('KML')
dataSource = driver.Open(fn, 0)
layer = dataSource.GetLayer()
I am also able to iterate over the features in the layer but from here on I can't seem to find the right way to save each feature as a separate KML.
-
Create a template KML with placeholders for substitution with placemarks you select from the source KML.swatchai– swatchai2018年02月13日 05:52:47 +00:00Commented Feb 13, 2018 at 5:52
-
Can you give me an example on how to do so?user88484– user884842018年02月13日 07:12:36 +00:00Commented Feb 13, 2018 at 7:12
2 Answers 2
Try the following script:
from osgeo import ogr
fn = r'C:\Users\kml folder\terre.kml'
driver = ogr.GetDriverByName('KML')
dataSource = driver.Open(fn)
layer = dataSource.GetLayer()
sr = layer.GetSpatialRef() # Spatial Reference
dst = r"" # Output directory
new_feat = ogr.Feature(layer.GetLayerDefn()) # Dummy feature
for id, feat in enumerate(layer):
new_ds = driver.CreateDataSource(r"{}\feat_{}.kml".format(dst, id))
new_lyr = new_ds.CreateLayer('feat_{}'.format(id), sr, ogr.wkbPolygon) # You have to specify the geometry type the layer will contain here with an ogr constant. I assume it is polygon but it can be changed.
geom = feat.geometry().Clone()
new_feat.SetGeometry(geom)
new_lyr.CreateFeature(new_feat)
del new_ds, new_lyr
Note: this script won't save any attribute information. I'm not familiar with this type of file and don't know how it stores attribute data. In case it does it in the same way a shapefile does, a couple of lines will take care of that as well.
Here is an example code to demonstrate what I mentioned in the comment:
# Simple KML template with `%s` as a place-holder for future text substitution
template = \
r"""<?xml version="1.0" encoding="utf-8" ?>
<kml xmlns="http://www.opengis.net/kml/2.2">
<Document id="root_doc">
<Folder>
<name>points_near_home</name>
%s
</Folder>
</Document>
</kml>"""
Example code representing collection of placemarks selected from another KML file:
pmarks = \
r"""<Placemark><Point><coordinates>100.560659,13.743991</coordinates></Point></Placemark>
<Placemark><Point><coordinates>100.560763,13.748826</coordinates></Point></Placemark>"""
# Push the content of pmarks into the template
fullkml = (template % pmarks).translate(None, '\n\t\r')
And, fullkml
has a complete KML code.