Fast KML processing in Python

1.4.0 · active · verified Thu Apr 16

fastkml is a Python library for creating, parsing, and modifying Keyhole Markup Language (KML) documents. It provides a fast and efficient way to work with KML files, supporting KML 2.2 specification features like Placemarks, Paths, Polygons, and TimeStamp. The current stable version is 1.4.0, and it maintains an active development pace with regular updates.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a basic KML document containing a single Placemark with a Point geometry, and then serialize it to a string. It also includes commented-out code showing how to parse a KML string back into objects.

from fastkml import KML
from fastkml.features import Placemark, Document
from fastkml.geometry import Point
import io

# Create a KML object
k = KML()
ns = '{http://www.opengis.net/kml/2.2}' # KML namespace

# Create a Document and append it to KML
doc = Document(ns, 'mydoc', 'My Document', 'This is a sample KML document.')
k.append_child(doc)

# Create a Placemark and append it to the Document
p = Placemark(ns, 'myplacemark', 'My First Placemark', 'This is a point of interest.')
p.geometry = Point(0, 52.1) # (longitude, latitude)
doc.append_child(p)

# Serialize the KML object to a string
kml_string = k.to_string(prettyprint=True)
print(kml_string)

# To parse from a string:
# kml_parsed = KML()
# kml_parsed.from_string(kml_string)
# for feature in kml_parsed.features():
#     if isinstance(feature, Document):
#         for sub_feature in feature.features():
#             if isinstance(sub_feature, Placemark):
#                 print(f"Parsed Placemark: {sub_feature.name} at {sub_feature.geometry.coords}")

view raw JSON →