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.
pip install fastkmlVerified import paths — ran on the pinned version, not inferred.
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.
Ensure geometry objects are `pygeoif` types. If you have a `shapely.geometry.Point`, construct a `fastkml.geometry.Point` (which is a `pygeoif` object) from its coordinates, e.g., `p.geometry = Point(shapely_point.x, shapely_point.y)`.
Always pass the KML namespace `ns = '{http://www.opengis.net/kml/2.2}'` as the first argument when instantiating KML objects like `Document(ns, ...)` or `Placemark(ns, ...)`.Migrate any usage of `fastkml.alt_kml` to the standard `fastkml.KML`, `fastkml.features`, and `fastkml.geometry` modules. The API changed significantly, so refer to the 1.0.0+ documentation for the correct approach.
Convert your geometry to a `pygeoif` object first. For example, if you have a `shapely_point = shapely.geometry.Point(0, 0)`, create `fastkml_point = fastkml.geometry.Point(shapely_point.x, shapely_point.y)` and assign `placemark.geometry = fastkml_point`.
Verify the KML content for correctness and ensure it's a well-formed XML document conforming to the KML specification. Check for correct encoding (usually UTF-8) and ensure the file/string isn't empty.
For files, ensure you're passing an opened file handle (e.g., `with open('my.kml', 'rb') as f: k.from_file(f)`). For strings, ensure the data is truly a string or bytes. If you have a file path, open it first.