Reference Guide

Fastkml is a library to read, write and manipulate kml files.

It aims to keep it simple and fast (using lxml if available). Fast refers to the time you spend to write and read KML files as well as the time you spend to get acquainted to the library or to create KML objects. 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.

fastkml.kml

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/.

class fastkml.kml.KML(ns: str | None = None, name_spaces: dict[str, str] | None = None, features: Iterable[Folder | Document | Placemark | GroundOverlay | PhotoOverlay | NetworkLinkControl] | None = None, **kwargs: Any)[source]

Bases: _XMLObject

represents a KML File.

append(kmlobj: Folder | Document | Placemark | GroundOverlay | PhotoOverlay | NetworkLinkControl) None[source]

Append a feature.

etree_element(precision: int | None = None, verbosity: Verbosity = Verbosity.normal) Element[source]

Return an Element object representing the KML element.

Parameters:
  • precision (Optional[int]) – The precision used for floating-point values.

  • verbosity (Verbosity) – The verbosity level for generating the KML element.

Returns:

The etree Element object representing the KML element.

Return type:

Element

features: list[Folder | Document | Placemark | GroundOverlay | PhotoOverlay | NetworkLinkControl]
classmethod get_tag_name() str[source]

Return the tag name.

ns: str
classmethod parse(file: Path | str | IO, *, ns: str | None = None, name_spaces: dict[str, str] | None = None, strict: bool = True, validate: bool | None = None) Self[source]

Parse a KML file and return a KML object.

Parameters:

file – The file to parse. Can be a file path or a file-like object.

Keyword Arguments:
  • ns (Optional[str]) – The namespace of the KML file. If not provided, it will be inferred from the root element.

  • name_spaces (Optional[Dict[str, str]]) – Additional namespaces.

  • strict (bool) – Whether to enforce strict parsing rules. Defaults to True.

  • validate (Optional[bool]) – Whether to validate the file against the schema.

Returns:

KML object: The parsed KML object.

write(file_path: Path, *, prettyprint: bool = True, precision: int | None = None, verbosity: Verbosity = Verbosity.normal) None[source]

Write KML to a file.

Parameters:
  • file_path – The file name where to save the file. Can be any string value

  • prettyprint (bool) – default=True Whether to pretty print the XML.

  • precision (Optional[int]) – The precision used for floating-point values.

  • verbosity (Verbosity) – The verbosity level for generating the KML element.

fastkml.base

Abstract XML base class.

The purpose of _XMLObject is to serve as a base class for KML objects in fastkml. Its main functions are:

  • Provide a common interface for XML serialization and deserialization.

  • Handle namespace management for KML elements.

  • Manage attribute storage and retrieval for derived classes.

  • Provide the etree_element() method for converting objects to XML Elements.

  • Facilitate integration with the registry system for flexible XML mapping.

By inheriting from _XMLObject, KML classes gain these capabilities, ensuring consistent handling of XML operations across the library.

class fastkml.base._XMLObject(ns: str | None = None, name_spaces: dict[str, str] | None = None, **kwargs: Any)[source]

Bases: object

XML Baseclass.

__init__(ns: str | None = None, name_spaces: dict[str, str] | None = None, **kwargs: Any) None[source]

Initialize the XML Object.

Parameters:
  • ns (Optional[str], default=None) – The namespace of the XML object.

  • name_spaces (Optional[Dict[str, str]], default=None) – The dictionary of namespace prefixes and URIs.

  • **kwargs (Any) – Additional keyword arguments.

classmethod _get_kwargs(*, ns: str, name_spaces: dict[str, str] | None = None, element: Element, strict: bool) dict[str, Any][source]

Get the keyword arguments for the class constructor.

A class method used for XML deserialization. Its main purposes are:

  • Extract attribute values from an XML element.

  • Convert these values into appropriate Python types.

  • Prepare a dictionary of keyword arguments for object initialization.

  • It is called during the parsing process to populate object attributes from XML data. The method uses the registry and helper functions to handle different attribute types and nested objects.

Subclasses may override this method to add custom deserialization logic for specific KML elements, although this should be rare. Prefer registration over a custom _get_kwargs implementation to ensure consistent handling of KML:

  • Consistency: Ensures uniform handling across all KML elements.

  • Maintainability: Centralizes parsing logic, making updates easier.

  • Declarative approach: Simplifies code by moving logic to configuration.

  • Reusability: Allows sharing of parsing logic across different classes.

  • Separation of concerns: Keeps parsing logic separate from class definitions.

  • Extensibility: Makes it easier to add new attributes or change parsing behavior.

  • Reduced duplication: Avoids repeating similar parsing code in multiple classes.

  • Easier testing: Allows testing of parsing logic independently of class implementations.

Parameters:
  • ns (str) – The namespace.

  • name_spaces (Optional[Dict[str, str]], default=None) – The dictionary of namespace prefixes and URIs.

  • element (Element) – The XML element.

  • strict (bool) – Whether to enforce strict parsing.

Returns:

The keyword arguments for the class constructor.

Return type:

Dict[str, Any]

etree_element(precision: int | None = None, verbosity: Verbosity = Verbosity.normal) Element[source]

Return the KML Object as an Element.

This method essentially converts the Python object to its XML representation, using the registry to determine how each attribute should be serialized.

  • Create an XML Element with the object’s tag name and namespace.

  • Iterate through registered attributes for the object’s class. For each attribute:

    • Call the corresponding set_element function. This function adds the attribute to the Element as a sub-element or attribute.

  • Handle different data types and nested objects.

  • Apply precision and verbosity settings if specified.

  • Return the complete Element tree representing the object.

Parameters:
  • precision (Optional[int], default=None) – The precision of the KML object.

  • verbosity (Verbosity, default=Verbosity.normal) – The verbosity level.

Returns:

The KML object as an Element.

Return type:

Element

classmethod from_string(string: str, *, ns: str | None = None, name_spaces: dict[str, str] | None = None, strict: bool = True) Self[source]

Create an XML object from a string.

Parameters:
  • string (str) – The string representation of the XML object.

  • ns (Optional[str], default=None) – The namespace of the XML object.

  • name_spaces (Optional[Dict[str, str]], default=None) – The dictionary of namespace prefixes and URIs.

  • strict (bool, default=True) – Whether to enforce strict parsing.

Returns:

The XML object.

Return type:

Self

to_string(*, prettyprint: bool = True, precision: int | None = None, verbosity: Verbosity = Verbosity.normal) str[source]

Return the KML Object as serialized xml.

Parameters:
  • prettyprint (bool, default=True) – Whether to pretty print the XML.

  • precision (Optional[int], default=None) – The precision of the KML object.

  • verbosity (Verbosity, default=Verbosity.normal) – The verbosity level.

Returns:

The KML object as serialized XML.

Return type:

str

validate() bool | None[source]

Validate the KML object against the XML schema.

Returns:

True if the object is valid, None if the XMLSchema is not available.

Return type:

Optional[bool]

Raises:

AssertionError – If the object is not valid.

fastkml.registry

Registry for XML objects.

The Registry is used to store and retrieve information about XML objects. This approach allows for flexible, declarative mapping between XML and Python objects, with the registry acting as a central configuration for these mappings.

fastkml.registry.registry

Global Registry.

You should use registry.registry instead of instantiating registry.Registry() because registry.registry is a pre-instantiated global instance, ensuring a single, shared registry across the entire application. It is pre-populated with all the necessary KML element registrations. If you need to add custom elements, you can extend the existing registry without creating a new one. Using the pre-defined registry.registry ensures you’re working with the complete, properly initialized registry for the fastkml library.

class fastkml.registry.Registry(registry: dict[type[_XMLObject], list[RegistryItem]] | None = None)[source]

Bases: object

A registry of XML objects.

The registry acts as a configuration hub, allowing the library to dynamically handle various KML elements and their attributes without hardcoding the logic into each class.

The purpose of the registry is to:

  • Centralize XML mapping configuration for KML objects.

  • Define attribute-to-element/attribute mappings.

  • Specify parsing and serialization functions for each attribute.

  • Support inheritance in XML mappings.

  • Provide a flexible, declarative approach to XML handling.

  • Decouple XML parsing/serialization logic from class definitions.

  • Allow easy addition or modification of XML mappings.

  • Enable consistent handling of attributes across different KML classes.

  • Facilitate extensibility and maintainability of the library.

get(cls: type[_XMLObject]) list[RegistryItem][source]

Get the registry items for a class and its ancestors.

The get method of the registry, in conjunction with _XMLObject:

  • Retrieves all registered items for a given class and its ancestors.

  • Supports inheritance in XML mappings.

  • Allows _XMLObject to dynamically determine how to parse/serialize attributes.

  • Enables flexible XML handling without hardcoding in each class.

  • Facilitates polymorphic behavior in XML parsing and serialization.

It allows _XMLObject to handle different KML elements consistently while respecting their inheritance structure.

register(cls: type[_XMLObject], item: RegistryItem) None[source]

Register a class.

Add a new RegistryItem to the registry for a specific class.

  • Appends the item to an existing list if the class is already registered.

  • Creates a new list with the item if it’s the first for that class.

  • Associates XML parsing/serialization rules with a class attribute.

  • Defines how a specific attribute should be handled in XML operations.

  • Allows for multiple registrations per class, supporting complex mappings.

  • Is called during library initialization to set up KML mappings.

This is the primary way to configure how different KML elements and their attributes are processed in fastkml.

class fastkml.registry.RegistryItem(ns_ids: tuple[str, ...], classes: tuple[type[object], ...], attr_name: str, get_kwarg: GetKWArgs, set_element: SetElement, node_name: str, default: Any = None, custom_get_kwarg: CustomGetKWArgs | None = None)[source]

Bases: object

A registry item.

The RegistryItem class is a dataclass that represents a single mapping between an XML object and a Python object. It contains the following fields:

  • ns_ids: A tuple of namespace identifiers that the mapping applies to.

  • classes: A tuple of Python classes that the mapping applies to.

  • attr_name: The name of the attribute on the Python object that corresponds to the XML object.

  • get_kwarg: A function that retrieves keyword arguments for the Python object.

  • set_element: A function that sets the XML element for the Python object.

  • type: The type of the XML object.

  • node_name: The name of the XML node that the mapping applies to.

  • default: An optional default value for the Python object attribute.

  • custom_get_kwarg: An optional custom function that retrieves keyword arguments for the Python object.

attr_name: str
classes: tuple[type[object], ...]
custom_get_kwarg: CustomGetKWArgs | None = None
default: Any = None
get_kwarg: GetKWArgs
node_name: str
ns_ids: tuple[str, ...]
set_element: SetElement

fastkml.kml_base

Abstract KML base class.

It adapts the generic XML functionality of _XMLObject to the specific needs of KML elements, providing a foundation for all KML-specific classes in fastkml.

  • Serve as the base class for all KML objects

  • Implement common KML attributes like ‘id’ and ‘target_id’

  • Set the default namespace to KML

  • Provide KML-specific initialization logic

  • Act as an intermediary between _XMLObject and concrete KML classes

  • Ensure consistent handling of basic KML properties across all elements

  • Facilitate KML-specific functionality while inheriting generic XML capabilities

class fastkml.kml_base._BaseObject(ns: str | None = None, name_spaces: dict[str, str] | None = None, id: str | None = None, target_id: str | None = None, **kwargs: Any)[source]

Bases: _XMLObject

Base class for all KML objects.

This is an abstract base class and cannot be used directly in a KML file. It provides the id attribute, which allows unique identification of a KML element, and the targetId attribute, which is used to reference objects that have already been loaded into Google Earth. The id attribute must be assigned if the <Update> mechanism is to be used.

__init__(ns: str | None = None, name_spaces: dict[str, str] | None = None, id: str | None = None, target_id: str | None = None, **kwargs: Any) None[source]

Initialize the KML Object.

Parameters:
  • ns ((Optional[str])) – The namespace of the KML object.

  • name_spaces ((Optional[Dict[str, str]])) – The dictionary of namespace prefixes and URIs.

  • id ((Optional[str])) – The id attribute of the KML object.

  • target_id ((Optional[str])) – The targetId attribute of the KML object.

  • kwargs ((Any)) – Additional keyword arguments.

Return type:

None

fastkml.helpers

Helper functions for fastkml.

The helpers module acts as a bridge between the abstract registry definitions and the concrete XML operations performed by _XMLObject.

  • Provides utility functions for XML parsing and serialization referenced in the registry for handling different data types.

  • Implements get_kwarg and set_element functions used by _XMLObject.

  • Offers helper functions for common operations like text handling and type conversions.

_XMLObject uses these helpers indirectly through the registry. The registry references these helper functions for attribute parsing and serialization. They form the implementation layer for the declarative approach defined by the registry.

fastkml.helpers.attribute_enum_kwarg(*, element: Element, ns: str, name_spaces: dict[str, str], node_name: str, kwarg: str, classes: tuple[type[object], ...], strict: bool) dict[str, Enum][source]

Return a dictionary with the specified keyword argument and its enum value.

Args:

element (Element): The XML element. ns (str): The namespace of the XML element. name_spaces (Dict[str, str]): A dictionary of namespace prefixes and their URIs. node_name (str): The name of the XML node. kwarg (str): The name of the keyword argument. classes (Tuple[Type[object], …]): A tuple of enum classes. strict (bool): A flag indicating whether to raise an error for invalid values.

Returns:

Dict[str, Enum]: A dictionary with the specified keyword argument and its value.

fastkml.helpers.attribute_float_kwarg(*, element: Element, ns: str, name_spaces: dict[str, str], node_name: str, kwarg: str, classes: tuple[type[object], ...], strict: bool) dict[str, float][source]

Convert an attribute value to a float and return it as a dictionary.

Args:

element (Element): The XML element containing the attribute. ns (str): The namespace of the attribute. name_spaces (Dict[str, str]): A dictionary of namespace prefixes and URIs. node_name (str): The name of the attribute. kwarg (str): The name of the keyword argument to store the converted float. classes (Tuple[Type[object], …]): A tuple of known types for error handling. strict (bool): A flag indicating whether to raise an error for invalid values.

Returns:

Dict[str, float]: A dictionary containing the float as a keyword argument.

Raises:

ValueError: If the attribute value cannot be converted to a float.

fastkml.helpers.attribute_int_kwarg(*, element: Element, ns: str, name_spaces: dict[str, str], node_name: str, kwarg: str, classes: tuple[type[object], ...], strict: bool) dict[str, int][source]

Extract an integer attribute from an XML element and return it as a dictionary.

Args:

element (Element): The XML element to extract the attribute from. ns (str): The namespace of the attribute. name_spaces (Dict[str, str]): A dictionary mapping namespace prefixes to URIs. node_name (str): The name of the XML node containing the attribute. kwarg (str): The name of the keyword argument to store the extracted attribute. classes (Tuple[Type[object], …]): A tuple of known types (unused). strict (bool): A flag indicating whether to raise an exception (unused).

Returns:

Dict[str, int]: A dictionary containing the extracted attribute value.

fastkml.helpers.attribute_text_kwarg(*, element: Element, ns: str, name_spaces: dict[str, str], node_name: str, kwarg: str, classes: tuple[type[object], ...], strict: bool) dict[str, str][source]

Return a dictionary representing the attribute as a keyword argument.

Args:

element (Element): The XML element. ns (str): The namespace of the attribute. name_spaces (Dict[str, str]): A dictionary mapping namespace prefixes to URIs. node_name (str): The name of the XML node. kwarg (str): The name of the keyword argument. classes (Tuple[Type[object], …]): A tuple of known types. strict (bool): A flag indicating whether to enforce strict parsing.

Returns:

Dict[str, str]: A dictionary representing the attribute as a keyword argument.

fastkml.helpers.bool_subelement(obj: _XMLObject, *, element: Element, attr_name: str, node_name: str, precision: int | None, verbosity: Verbosity, default: bool | None) None[source]

Set the value of an attribute from a subelement with a text node.

Args:

obj (“_XMLObject”): The object from which to retrieve the attribute value. element (Element): The parent element to add the subelement to. attr_name (str): The name of the attribute to retrieve the value from. node_name (str): The name of the subelement to create. precision (Optional[int]): The precision of the attribute value. verbosity (Optional[Verbosity]): The verbosity level. default (Optional[bool]): The default value for the attribute.

Returns:

None

fastkml.helpers.clean_string(value: str | None) str | None[source]

Clean and validate a string value, returning None if empty.

fastkml.helpers.coords_subelement_list(obj: _XMLObject, *, element: Element, attr_name: str, node_name: str, precision: int | None, verbosity: Verbosity, default: str | None) None[source]

Create the subelements for a list of KML coordinate values.

fastkml.helpers.coords_subelement_list_kwarg(*, element: Element, ns: str, name_spaces: dict[str, str], node_name: str, kwarg: str, classes: tuple[type[object], ...], strict: bool) dict[str, list[tuple[float, float] | tuple[float, float, float]]][source]

Extract a list of KML coordinate values from subelements of an XML element.

fastkml.helpers.datetime_subelement(obj: _XMLObject, *, element: Element, attr_name: str, node_name: str, precision: int | None, verbosity: Verbosity, default: str | None) None[source]

Create the subelement for a KML datetime values.

fastkml.helpers.datetime_subelement_kwarg(*, element: Element, ns: str, name_spaces: dict[str, str], node_name: str, kwarg: str, classes: tuple[type[object], ...], strict: bool) dict[str, KmlDateTime][source]

Extract a KML datetime from a subelement of an XML element.

fastkml.helpers.datetime_subelement_list(obj: _XMLObject, *, element: Element, attr_name: str, node_name: str, precision: int | None, verbosity: Verbosity, default: str | None) None[source]

Create the subelements for a list of KML datetime values.

fastkml.helpers.datetime_subelement_list_kwarg(*, element: Element, ns: str, name_spaces: dict[str, str], node_name: str, kwarg: str, classes: tuple[type[object], ...], strict: bool) dict[str, list[KmlDateTime]][source]

Extract a list of KML datetime values from subelements of an XML element.

fastkml.helpers.enum_attribute(obj: _XMLObject, *, element: Element, attr_name: str, node_name: str, precision: int | None, verbosity: Verbosity, default: Enum | None) None[source]

Set the value of an attribute.

fastkml.helpers.enum_subelement(obj: _XMLObject, *, element: Element, attr_name: str, node_name: str, precision: int | None, verbosity: Verbosity, default: Enum | None) None[source]

Set the value of an attribute from a subelement with a text node.

fastkml.helpers.float_attribute(obj: _XMLObject, *, element: Element, attr_name: str, node_name: str, precision: int | None, verbosity: Verbosity, default: float | None) None[source]

Set the value of an attribute.

fastkml.helpers.float_subelement(obj: _XMLObject, *, element: Element, attr_name: str, node_name: str, precision: int | None, verbosity: Verbosity, default: float | None) None[source]

Set the value of an attribute from a subelement with a text node.

fastkml.helpers.get_coord_args(element: Element, subelements: Iterable[Element], strict: bool) Iterable[tuple[float, float] | tuple[float, float, float]][source]

Extract a list of KML coordinate values from subelements of an XML element.

fastkml.helpers.get_ns(obj: _XMLObject, value: object) str[source]

Get the namespace of an attribute, fall back on the objects namespace.

fastkml.helpers.get_value(obj: _XMLObject, *, attr_name: str, verbosity: Verbosity, default: Any | None) Any | None[source]

Get the value of an attribute from an object.

If the verbosity is set to Verbosity.terse, the function returns None if the attribute value is equal to the default value. If the verbosity is set to Verbosity.verbose, the function returns the default value if the attribute value is None.

Args:

obj (“_XMLObject”): The object to get the attribute value from. attr_name (str): The name of the attribute to retrieve. verbosity (Optional[Verbosity]): The verbosity. default (Optional[Any]): The default value.

fastkml.helpers.handle_error(*, error: Exception, strict: bool, element: Element, node: Element, expected: str) None[source]

Handle an error.

Args:

error (Exception): The exception that occurred. strict (bool): A flag indicating whether to raise an exception or log a warning. element (Element): The XML element being parsed. node (Element): The XML node that caused the error. expected (str): The expected format or value.

Raises:

KMLParseError: If strict is True, the function raises a KMLParseError with the error message.

fastkml.helpers.int_attribute(obj: _XMLObject, *, element: Element, attr_name: str, node_name: str, precision: int | None, verbosity: Verbosity, default: int | None) None[source]

Set the value of an attribute.

Args:

obj (“_XMLObject”): The object from which to retrieve the attribute value. element (Element): The parent element to add the subelement to. attr_name (str): The name of the attribute to retrieve the value from. node_name (str): The name of the attribute to be set. precision (Optional[int]): The precision of the attribute value. verbosity (Optional[Verbosity]): The verbosity level. default (Optional[int]): The default value for the attribute.

Returns:

None: This function does not return anything.

fastkml.helpers.int_subelement(obj: _XMLObject, *, element: Element, attr_name: str, node_name: str, precision: int | None, verbosity: Verbosity, default: int | None) None[source]

Set the value of an attribute from a subelement with a text node.

Args:

obj (“_XMLObject”): The object from which to retrieve the attribute value. element (Element): The parent element to add the subelement to. attr_name (str): The name of the attribute to retrieve the value from. node_name (str): The name of the subelement to create. precision (Optional[int]): The precision of the attribute value. verbosity (Optional[Verbosity]): The verbosity level. default (Optional[int]): The default value for the attribute.

Returns:

None: This function does not return anything.

fastkml.helpers.node_text(obj: _XMLObject, *, element: Element, attr_name: str, node_name: str, precision: int | None, verbosity: Verbosity, default: str | None) None[source]

Set the text of an XML element based on the attribute value in the given object.

Parameters:
  • obj ("_XMLObject") – The object containing the attribute value.

  • element (Element) – The XML element to set the text content for.

  • attr_name (str) – The name of the attribute in the object.

  • node_name (str) – The name of the XML node (unused).

  • precision (Optional[int]) – The precision to use when converting numeric values to text (unused).

  • verbosity (Optional[Verbosity]) – The verbosity level for logging (unused).

  • default (Optional[str]) – The default value for the attribute.

Returns:

This function does not return anything.

Return type:

None

fastkml.helpers.node_text_kwarg(*, element: Element, ns: str, name_spaces: dict[str, str], node_name: str, kwarg: str, classes: tuple[type[object], ...], strict: bool) dict[str, str][source]

Extract the text content of an XML element and return it as a dictionary.

Args:

element (Element): The XML element to extract the text content from. ns (str): The namespace of the XML element. name_spaces (Dict[str, str]): A dictionary mapping namespace prefixes to their URIs. node_name (str): The name of the XML node. kwarg (str): The name of the keyword argument to store the text content in. classes (Tuple[Type[object], …]): A tuple of known types. strict (bool): A flag indicating whether to enforce strict parsing rules.

Returns:

Dict[str, str]: A dictionary containing the keyword argument and its

corresponding text content, if it exists.

fastkml.helpers.subelement_bool_kwarg(*, element: Element, ns: str, name_spaces: dict[str, str], node_name: str, kwarg: str, classes: tuple[type[object], ...], strict: bool) dict[str, bool][source]

Extract a boolean value from a subelement of an XML element.

Args:

element (Element): The XML element to search for the subelement. ns (str): The namespace of the subelement. name_spaces (Dict[str, str]): A dictionary mapping namespace prefixes to URIs. node_name (str): The name of the subelement. kwarg (str): The name of the keyword argument to store the boolean value. classes (Tuple[Type[object], …]): A tuple of known types. strict (bool): A flag indicating whether to enforce strict parsing.

Returns:

Dict[str, bool]: A dictionary containing the keyword argument and its value.

Raises:

ValueError: If the value of the subelement is not a valid boolean.

fastkml.helpers.subelement_enum_kwarg(*, element: Element, ns: str, name_spaces: dict[str, str], node_name: str, kwarg: str, classes: tuple[type[object], ...], strict: bool) dict[str, Enum][source]

Extract an enumerated value from a subelement of an XML element.

Args:

element (Element): The XML element to search for the subelement. ns (str): The namespace of the subelement. name_spaces (Dict[str, str]): A dictionary of namespace prefixes and URIs. node_name (str): The name of the subelement. kwarg (str): The name of the keyword argument to store the extracted value. classes (Tuple[Type[object], …]): A tuple of enumerated value classes. strict (bool): A flag indicating whether to raise an exception.

Returns:

Dict[str, Enum]: A dictionary containing the extracted enumerated value.

Raises:

ValueError: If the extracted value is not a valid enumerated value and strict.

fastkml.helpers.subelement_float_kwarg(*, element: Element, ns: str, name_spaces: dict[str, str], node_name: str, kwarg: str, classes: tuple[type[object], ...], strict: bool) dict[str, float][source]

Extract a float value from a subelement of an XML element.

Args:

element (Element): The XML element to search for the subelement. ns (str): The namespace of the subelement. name_spaces (Dict[str, str]): A dictionary of namespace prefixes and URIs. node_name (str): The name of the subelement. kwarg (str): The name of the keyword argument to store the float value. classes (Tuple[Type[object], …]): A tuple of known types for error handling. strict (bool): A flag indicating whether to raise an error.

Returns:

Dict[str, float]: A dictionary containing the float value as a keyword argument.

Raises:

ValueError: If the value of the subelement cannot be converted and strict.

fastkml.helpers.subelement_int_kwarg(*, element: Element, ns: str, name_spaces: dict[str, str], node_name: str, kwarg: str, classes: tuple[type[object], ...], strict: bool) dict[str, int][source]

Extract an integer value from a subelement of an XML element.

Args:

element (Element): The XML element to search for the subelement. ns (str): The namespace of the subelement. name_spaces (Dict[str, str]): A dictionary mapping namespace prefixes to URIs. node_name (str): The name of the subelement. kwarg (str): The key to use in the returned dictionary. classes (Tuple[Type[object], …]): A tuple of known types for error handling. strict (bool): A flag indicating whether to enforce strict parsing.

Returns:

Dict[str, int]: A dictionary containing the keyword argument and its value.

Raises:

ValueError: If the value of the subelement is not a valid integer and strict.

fastkml.helpers.subelement_text_kwarg(*, element: Element, ns: str, name_spaces: dict[str, str], node_name: str, kwarg: str, classes: tuple[type[object], ...], strict: bool) dict[str, str][source]

Extract the text content of a subelement and return it as a dictionary.

Args:

element (Element): The parent element. ns (str): The namespace of the subelement. name_spaces (Dict[str, str]): A dictionary of namespace prefixes and URIs. node_name (str): The name of the subelement. kwarg (str): The key to use in the returned dictionary. classes (Tuple[Type[object], …]): A tuple of known types. strict (bool): A flag indicating whether to enforce strict parsing.

Returns:

Dict[str, str]: A dictionary containing the extracted text content,

with the specified key.

fastkml.helpers.text_attribute(obj: _XMLObject, *, element: Element, attr_name: str, node_name: str, precision: int | None, verbosity: Verbosity, default: str | None) None[source]

Set the value of an attribute from a subelement with a text node.

Args:

obj (“_XMLObject”): The object from which to retrieve the attribute value. element (Element): The parent element to add the subelement to. attr_name (str): The name of the attribute to retrieve the value from. node_name (str): The name of the attribute to be set. precision (Optional[int]): The precision of the attribute value. verbosity (Optional[Verbosity]): The verbosity level. default (Optional[str]): The default value for the attribute.

Returns:

None

fastkml.helpers.text_subelement(obj: _XMLObject, *, element: Element, attr_name: str, node_name: str, precision: int | None, verbosity: Verbosity, default: str | None) None[source]

Set the value of an attribute from a subelement with a text node.

Args:

obj (“_XMLObject”): The object from which to retrieve the attribute value. element (Element): The parent element to add the subelement to. attr_name (str): The name of the attribute to retrieve the value from. node_name (str): The name of the subelement to create. precision (Optional[int]): The precision of the attribute value. verbosity (Optional[Verbosity]): The verbosity level. default (Optional[str]): The default value for the attribute.

Returns:

None

fastkml.helpers.xml_subelement(obj: _XMLObject, *, element: Element, attr_name: str, node_name: str, precision: int | None, verbosity: Verbosity, default: _XMLObject | None) None[source]

Add a subelement to an XML element based on the value of an attribute of an object.

Args:

obj (“_XMLObject”): The object containing the attribute. element (Element): The XML element to which the subelement will be added. attr_name (str): The name of the attribute in the object. node_name (str): The name of the XML node for the subelement (unused). precision (Optional[int]): The precision for formatting numerical values. verbosity (Optional[Verbosity]): The verbosity level for the subelement. default (Optional[“_XMLObject”]): The default value for the attribute (unused).

Returns:

None

fastkml.helpers.xml_subelement_kwarg(*, element: Element, ns: str, name_spaces: dict[str, str], node_name: str, kwarg: str, classes: tuple[type[object], ...], strict: bool) dict[str, _XMLObject][source]

Return the subelement of the given XML element based on the provided parameters.

Args:

element (Element): The XML element to search within. ns (str): The namespace of the XML element. name_spaces (Dict[str, str]): A dictionary mapping namespace prefixes to their URIs. node_name (str): The name of the XML node to search for. kwarg (str): The name of the keyword argument to store the found subelement. classes (Tuple[Type[object], …]): A tuple of classes that represent the types. strict (bool): A flag indicating whether to enforce strict parsing rules.

Returns:

Dict[str, “_XMLObject”]: A dictionary containing the found subelement as the value

of the specified keyword argument.

fastkml.helpers.xml_subelement_list(obj: _XMLObject, *, element: Element, attr_name: str, node_name: str, precision: int | None, verbosity: Verbosity, default: list[_XMLObject] | None) None[source]

Add subelements to an XML element based on a list attribute of an object.

Args:

obj (“_XMLObject”): The object containing the list attribute. element (Element): The XML element to which the subelements will be added. attr_name (str): The name of the list attribute in the object. node_name (str): The name of the XML node for each subelement (unused). precision (Optional[int]): The precision for floating-point values. verbosity (Optional[Verbosity]): The verbosity level for the XML output. default (Optional[List[“_XMLObject”]]): The default value for the attribute.

Returns:

None

fastkml.helpers.xml_subelement_list_kwarg(*, element: Element, ns: str, name_spaces: dict[str, str], node_name: str, kwarg: str, classes: tuple[type[object], ...], strict: bool) dict[str, list[_XMLObject]][source]

Return a dictionary with the specified keyword argument and its list of subelements.

Args:

element (Element): The XML element to search within. ns (str): The namespace of the XML element. name_spaces (Dict[str, str]): A dictionary mapping namespace prefixes to URIs. node_name (str): The name of the XML node to search for. kwarg (str): The name of the keyword argument to store the found subelements. classes (Tuple[Type[object], …]): A tuple of classes that represent the types. strict (bool): A flag indicating whether to enforce strict parsing rules.

Returns:

Dict[str, List[“_XMLObject”]]: A dictionary containing the specified keyword

argument and its list of subelements.

fastkml.about

About fastkml.

The only purpose of this module is to provide a version number for the package.

fastkml.about.__version__ = '1.4.0'

Fastkml version number.

fastkml.atom

Basic Atom support for KML.

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. The ascription elements used in KML are as follows:

atom:author element - parent element for atom:name atom:name element - the name of the author atom:link element - contains the href attribute href attribute - URL of the web page containing the KML/KMZ file

These elements are defined in the Atom Syndication Format. The complete specification is found at http://atompub.org.

This library only implements a subset of Atom that is useful with KML

class fastkml.atom.Author(ns: str | None = None, name_spaces: dict[str, str] | None = None, name: str | None = None, uri: str | None = None, email: str | None = None, **kwargs: Any)[source]

Bases: _Person

Return the names one author of the feed/entry.

A feed/entry may have multiple authors.

class fastkml.atom.Contributor(ns: str | None = None, name_spaces: dict[str, str] | None = None, name: str | None = None, uri: str | None = None, email: str | None = None, **kwargs: Any)[source]

Bases: _Person

Return the names one contributor to the feed/entry.

A feed/entry may have multiple contributor elements.

Bases: _AtomObject

Identifies a related Web page.

The rel attribute defines the type of relation. A feed is limited to one alternate per type and hreflang. <link> is patterned after html’s link element. It has one required attribute, href, and five optional attributes: rel, type, hreflang, title, and length.

href: str | None
hreflang: str | None
length: int | None
rel: str | None
title: str | None
type: str | None

fastkml.config

Frequently used constants and configuration options.

fastkml.config.register_namespaces(**namespaces: str) None[source]

Register namespaces for use in etree.ElementTree.parse().

fastkml.config.set_default_namespaces() None[source]

Register the default namespaces for use in etree.ElementTree.parse().

fastkml.config.set_etree_implementation(implementation: ModuleType) None[source]

Set the etree implementation to use.

fastkml.containers

Container classes for KML elements.

class fastkml.containers.Document(ns: str | None = None, name_spaces: dict[str, str] | None = None, id: str | None = None, target_id: str | None = None, name: str | None = None, visibility: bool | None = None, isopen: bool | None = None, atom_link: Link | None = None, atom_author: Author | None = None, address: str | None = None, phone_number: str | None = None, snippet: Snippet | None = None, description: str | None = None, view: Camera | LookAt | None = None, times: TimeSpan | TimeStamp | None = None, style_url: StyleUrl | None = None, styles: Iterable[Style | StyleMap] | None = None, region: Region | None = None, extended_data: ExtendedData | None = None, features: Iterable[_Feature] | None = None, schemata: Iterable[Schema] | None = None, **kwargs: Any)[source]

Bases: _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.

get_style_by_url(style_url: str) Style | StyleMap | None[source]

Get a style by URL.

Parameters:

style_url (str) – The URL of the style.

Returns:

The style object if found, otherwise None.

Return type:

Optional[Union[Style, StyleMap]]

schemata: list[Schema]
class fastkml.containers.Folder(ns: str | None = None, name_spaces: dict[str, str] | None = None, id: str | None = None, target_id: str | None = None, name: str | None = None, visibility: bool | None = None, isopen: bool | None = None, atom_link: Link | None = None, atom_author: Author | None = None, address: str | None = None, phone_number: str | None = None, snippet: Snippet | None = None, description: str | None = None, view: Camera | LookAt | None = None, times: TimeSpan | TimeStamp | None = None, style_url: StyleUrl | None = None, styles: Iterable[Style | StyleMap] | None = None, region: Region | None = None, extended_data: ExtendedData | None = None, features: Iterable[_Feature] | None = None, **kwargs: Any)[source]

Bases: _Container

A Folder is used to arrange other Features hierarchically.

It may contain Folders, Placemarks, NetworkLinks, or Overlays.

https://developers.google.com/kml/documentation/kmlreference#folder

fastkml.data

Add Custom Data.

https://developers.google.com/kml/documentation/extendeddata

class fastkml.data.Data(ns: str | None = None, name_spaces: dict[str, str] | None = None, id: str | None = None, target_id: str | None = None, name: str | None = None, value: str | None = None, display_name: str | None = None, **kwargs: Any)[source]

Bases: _BaseObject

Represents an untyped name/value pair with optional display name.

display_name: str | None
name: str | None
value: str | None
class fastkml.data.ExtendedData(ns: str | None = None, name_spaces: dict[str, str] | None = None, elements: Iterable[Data | SchemaData] | None = None, **kwargs: Any)[source]

Bases: _XMLObject

Represents a list of untyped name/value pairs.

elements: list[Data | SchemaData]
class fastkml.data.Schema(ns: str | None = None, name_spaces: dict[str, str] | None = None, id: str | None = None, name: str | None = None, fields: Iterable[SimpleField] | None = None, array_fields: Iterable[SimpleArrayField] | None = None, **kwargs: Any)[source]

Bases: _XMLObject

Specifies a custom KML schema that is used to add custom data to KML Features.

The “id” attribute is required and must be unique within the KML file. <Schema> is always a child of <Document>.

https://developers.google.com/kml/documentation/extendeddata#declare-the-schema-element

append(field: SimpleField | SimpleArrayField) None[source]

Append a field to the schema.

Parameters:

field (Union[SimpleField, SimpleArrayField]) – The field to be appended.

array_fields: list[SimpleArrayField]
fields: list[SimpleField]
name: str | None
class fastkml.data.SchemaData(ns: str | None = None, name_spaces: dict[str, str] | None = None, id: str | None = None, target_id: str | None = None, schema_url: str | None = None, data: Iterable[SimpleData] | None = None, array_data: Iterable[SimpleArrayData] | None = None, **kwargs: Any)[source]

Bases: _BaseObject

Represents the SchemaData element in KML.

The SchemaData element is used in conjunction with Schema to add typed custom data to a KML Feature. The Schema element (identified by the schemaUrl attribute) declares the custom data type. The actual data objects (“instances” of the custom data) are defined using the SchemaData element.

append_data(data: SimpleData | SimpleArrayData) None[source]

Append a data object to the SchemaData.

Args:

data (Union[SimpleData, SimpleArrayData]):

The data object to be appended.

array_data: list[SimpleArrayData]
data: list[SimpleData]
schema_url: str | None
class fastkml.data.SimpleData(ns: str | None = None, name_spaces: dict[str, str] | None = None, name: str | None = None, value: str | None = None, **kwargs: Any)[source]

Bases: _XMLObject

A SimpleData element is a custom data field.

This element assigns a value to the custom data field identified by the name attribute. The type and name of this custom data field are declared in the <Schema> element.

name: str | None
value: str | None
class fastkml.data.SimpleField(ns: str | None = None, name_spaces: dict[str, str] | None = None, name: str | None = None, type_: DataType | None = None, display_name: str | None = None, **kwargs: Any)[source]

Bases: _XMLObject

A SimpleField always has both name and type attributes.

The declaration of the custom field, must specify both the type and the name of this field. If either the type or the name is omitted, the field is ignored.

The type can be one of the following:
  • string

  • int

  • uint

  • short

  • ushort

  • float

  • double

  • bool

The displayName, if any, to be used when the field name is displayed to the Google Earth user. Use the [CDATA] element to escape standard HTML markup.

display_name: str | None
name: str | None
type_: DataType | None

fastkml.enums

Enums for the fastkml package.

This module contains the enums used in the fastkml package.

https://developers.google.com/kml/documentation/kmlreference#kml-fields

class fastkml.enums.AltitudeMode(value)[source]

Bases: RelaxedEnum

Enum to represent the different altitude modes.

Specifies how altitude components in the <coordinates> element are interpreted. Possible values are

  • clampToGround - (default) Indicates to ignore an altitude specification (for example, in the <coordinates> tag).

  • relativeToGround - Sets the altitude of the element relative to the actual ground elevation of a particular location. For example, if the ground elevation of a location is exactly at sea level and the altitude for a point is set to 9 meters, then the elevation for the icon of a point placemark elevation is 9 meters with this mode. However, if the same coordinate is set over a location where the ground elevation is 10 meters above sea level, then the elevation of the coordinate is 19 meters. A typical use of this mode is for placing telephone poles or a ski lift.

  • absolute - Sets the altitude of the coordinate relative to sea level, regardless of the actual elevation of the terrain beneath the element. For example, if you set the altitude of a coordinate to 10 meters with an absolute altitude mode, the icon of a point placemark 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 placemark will appear elevated above the terrain by 7 meters. A typical use of this mode is for aircraft placement.

  • relativeToSeaFloor - Interprets the altitude as a value in meters above the sea floor. If the point is above land rather than sea, the altitude will be interpreted as being above the ground.

  • clampToSeaFloor - The altitude specification is ignored, and the point will be positioned on the sea floor. If the point is on land rather than at sea, the point will be positioned on the ground.

The Values relativeToSeaFloor and clampToSeaFloor are not part of the KML definition but of the <gx:altitudeMode> a KML extension in the Google extension namespace, allowing altitudes relative to the sea floor.

absolute = 'absolute'
clamp_to_ground = 'clampToGround'
clamp_to_sea_floor = 'clampToSeaFloor'
get_ns_id() str[source]

Get the namespace for the altitude mode.

relative_to_ground = 'relativeToGround'
relative_to_sea_floor = 'relativeToSeaFloor'
class fastkml.enums.ColorMode(value)[source]

Bases: RelaxedEnum

Enum to represent the different color modes.

Specifies how the color is applied to the geometry.

normal = 'normal'
random = 'random'
class fastkml.enums.DataType(value)[source]

Bases: RelaxedEnum

Data type for SimpleField in extended data.

bool_ = 'bool'
double = 'double'
float_ = 'float'
int_ = 'int'
short = 'short'
string = 'string'
uint = 'uint'
ushort = 'ushort'
class fastkml.enums.DateTimeResolution(value)[source]

Bases: RelaxedEnum

Enum to represent the different date time resolutions.

date = 'date'
datetime = 'dateTime'
year = 'gYear'
year_month = 'gYearMonth'
class fastkml.enums.DisplayMode(value)[source]

Bases: RelaxedEnum

DisplayMode for BalloonStyle.

If <displayMode> is default, Google Earth uses the information supplied in <text> to create a balloon . If <displayMode> is hide, Google Earth does not display the balloon. In Google Earth, clicking the List View icon for a Placemark whose balloon’s <displayMode> is hide causes Google Earth to fly to the Placemark.

default = 'default'
hide = 'hide'
class fastkml.enums.GridOrigin(value)[source]

Bases: RelaxedEnum

GridOrigin for GroundOverlay.

Specifies where to begin numbering the tiles in each layer of the pyramid. A value of lowerLeft specifies that row 1, column 1 of each layer is in the bottom left corner of the grid.

lower_left = 'lowerLeft'
upper_left = 'upperLeft'
class fastkml.enums.PairKey(value)[source]

Bases: RelaxedEnum

Key for Pair.

highlight = 'highlight'
normal = 'normal'
class fastkml.enums.RefreshMode(value)[source]

Bases: RelaxedEnum

Enum to represent the different refresh modes.

Specifies how the link is refreshed when the “camera” changes.

on_change = 'onChange'
on_expire = 'onExpire'
on_interval = 'onInterval'
class fastkml.enums.RelaxedEnum(value)[source]

Bases: Enum

Enum with relaxed string value matching.

This class provides an enum with relaxed value matching, allowing case-insensitive comparison of enum values. If a value is not found in the enum, it will attempt to find a case-insensitive match. If no match is found, a ValueError is raised.

Usage:

To use this enum, simply subclass RelaxedEnum and define your enum values.

Example:

class AltitudeMode(RelaxedEnum):
    clamp_to_ground = "clampToGround"
    relative_to_ground = "relativeToGround"
    absolute = "absolute"

my_value = AltitudeMode("CLAMPTOGROUND")  # Case-insensitive match
print(my_value)  # Output: AltitudeMode.clamp_to_ground

The subclass must define all values as strings.

class fastkml.enums.Shape(value)[source]

Bases: RelaxedEnum

Shape for PhotoOverlay.

The PhotoOverlay is projected onto the <shape>. The <shape> can be one of the following: - rectangle (default) - for an ordinary photo - cylinder - for panoramas, which can be either partial or full cylinders - sphere - for spherical panoramas

cylinder = 'cylinder'
rectangle = 'rectangle'
sphere = 'sphere'
class fastkml.enums.Units(value)[source]

Bases: RelaxedEnum

Units for ScreenOverlay and Hotspot.

Specifies how the <x>, <y> values are interpreted.

fraction = 'fraction'
inset_pixels = 'insetPixels'
pixels = 'pixels'
class fastkml.enums.Verbosity(value)[source]

Bases: Enum

Enum to represent the different verbosity levels.

normal = 1
terse = 0
verbose = 2
class fastkml.enums.ViewRefreshMode(value)[source]

Bases: RelaxedEnum

Enum to represent the different view refresh modes.

Specifies how the link is refreshed when the “camera” changes.

never = 'never'
on_region = 'onRegion'
on_request = 'onRequest'
on_stop = 'onStop'

fastkml.exceptions

Exceptions for the fastkml package.

exception fastkml.exceptions.FastKMLError[source]

Bases: Exception

Base class for all fastkml exceptions.

exception fastkml.exceptions.GeometryError[source]

Bases: FastKMLError

Raised when there is an error with the geometry.

exception fastkml.exceptions.KMLParseError[source]

Bases: FastKMLError

Raised when there is an error parsing KML.

exception fastkml.exceptions.KMLSchemaError[source]

Bases: FastKMLError

Raised when there is an error with the KML Schema.

exception fastkml.exceptions.KMLWriteError[source]

Bases: FastKMLError

Raised when there is an error writing KML.

fastkml.features

Feature base, Placemark and NetworkLink.

These are the objects that can be added to a KML file.

Bases: _Feature

References a KML file or KMZ archive on a local or remote network.

Use the <Link> element to specify the location of the KML file. Within that element, you can define the refresh options for updating the file, based on time and camera change. NetworkLinks can be used in combination with Regions to handle very large datasets efficiently. https://developers.google.com/kml/documentation/kmlreference#networklink

Elements Specific to NetworkLink <refreshVisibility> Boolean value. A value of 0 leaves the visibility of features within the control of the Google Earth user. Set the value to 1 to reset the visibility of features each time the NetworkLink is refreshed. For example, suppose a Placemark within the linked KML file has <visibility> set to 1 and the NetworkLink has <refreshVisibility> set to 1. When the file is first loaded into Google Earth, the user can clear the check box next to the item to turn off display in the 3D viewer. However, when the NetworkLink is refreshed, the Placemark will be made visible again, since its original visibility state was TRUE. <flyToView> Boolean value. A value of 1 causes Google Earth to fly to the view of the LookAt or Camera in the NetworkLinkControl (if it exists). If the NetworkLinkControl does not contain an AbstractView element, Google Earth flies to the LookAt or Camera element in the Feature child within the <kml> element in the refreshed file. If the <kml> element does not have a LookAt or Camera specified, the view is unchanged. For example, Google Earth would fly to the <LookAt> view of the parent Document, not the <LookAt> of the Placemarks contained within the Document. <Link>(required)

https://developers.google.com/kml/documentation/kmlreference#networklink

fly_to_view: bool | None
refresh_visibility: bool | None
class fastkml.features.Placemark(ns: str | None = None, name_spaces: dict[str, str] | None = None, id: str | None = None, target_id: str | None = None, name: str | None = None, visibility: bool | None = None, isopen: bool | None = None, atom_link: Link | None = None, atom_author: Author | None = None, address: str | None = None, phone_number: str | None = None, snippet: Snippet | None = None, description: str | None = None, view: Camera | LookAt | None = None, times: TimeSpan | TimeStamp | None = None, style_url: StyleUrl | None = None, styles: Iterable[Style | StyleMap] | None = None, region: Region | None = None, extended_data: ExtendedData | None = None, kml_geometry: Point | LineString | LinearRing | Polygon | Model | MultiGeometry | MultiTrack | Track | None = None, geometry: GeoType | GeoCollectionType | None = None, **kwargs: Any)[source]

Bases: _Feature

A Placemark is a Feature with associated Geometry.

In Google Earth, a Placemark appears as a list item in the Places panel. A Placemark with a Point has an icon associated with it that marks a point on the Earth in the 3D viewer.

property geometry: Polygon | LineString | LinearRing | Point | MultiPoint | MultiLineString | MultiPolygon | GeometryCollection | None

Returns the geometry associated with this feature.

Returns:

  • Optional[AnyGeometryType] (The geometry associated with this feature,)

  • or None if no geometry is present.

kml_geometry: Point | LineString | LinearRing | Polygon | Model | MultiGeometry | MultiTrack | Track | None
class fastkml.features.Snippet(ns: str | None = None, name_spaces: dict[str, str] | None = None, text: str | None = None, max_lines: int | None = None, **kwargs: Any)[source]

Bases: _XMLObject

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.

max_lines: int | None = None
text: str | None

fastkml.geometry

Classes and functions for working with geometries in KML files.

The classes in this module represent different types of geometries, such as points, lines, polygons, and multi-geometries. These geometries can be used to define the shape and location of features in KML files.

The module also provides functions for handling coordinates and extracting them from XML elements.

class fastkml.geometry.Coordinates(*, ns: str | None = None, name_spaces: dict[str, str] | None = None, coords: Sequence[tuple[float, float]] | Sequence[tuple[float, float, float]] | None = None, **kwargs: Any)[source]

Bases: _XMLObject

Represents a set of coordinates in decimal degrees.

coords(LineType)

Each coord consists of floating point values for longitude, latitude, and altitude. The altitude component is optional. Coordinates are expressed in decimal degrees only.

Type:

A list of tuples representing the coordinates.

coords: Sequence[tuple[float, float]] | Sequence[tuple[float, float, float]]
classmethod get_tag_name() str[source]

Return the tag name.

class fastkml.geometry.InnerBoundaryIs(*, ns: str | None = None, name_spaces: dict[str, str] | None = None, geometry: LinearRing | None = None, kml_geometry: LinearRing | None = None, **kwargs: Any)[source]

Bases: BoundaryIs

Represents the inner boundary of a polygon in KML.

classmethod get_tag_name() str[source]

Return the tag name of the element.

class fastkml.geometry.LineString(*, ns: str | None = None, name_spaces: dict[str, str] | None = None, id: str | None = None, target_id: str | None = None, extrude: bool | None = None, tessellate: bool | None = None, altitude_mode: AltitudeMode | None = None, geometry: LineString | None = None, kml_coordinates: Coordinates | None = None, **kwargs: Any)[source]

Bases: _Geometry

Defines a connected set of line segments.

Use <LineStyle> to specify the color, color mode, and width of the line. When a LineString is extruded, the line is extended to the ground, forming a polygon that looks somewhat like a wall or fence. For extruded LineStrings, the line itself uses the current LineStyle, and the extrusion uses the current PolyStyle. See the KML Tutorial for examples of LineStrings (or paths).

https://developers.google.com/kml/documentation/kmlreference#linestring

extrude: bool | None
property geometry: LineString | None

Get the LineString geometry.

Returns:

  • Optional[geo.LineString] (The LineString geometry, or None if it doesn’t)

  • exist.

kml_coordinates: Coordinates | None
tessellate: bool | None
class fastkml.geometry.LinearRing(*, ns: str | None = None, name_spaces: dict[str, str] | None = None, id: str | None = None, target_id: str | None = None, extrude: bool | None = None, tessellate: bool | None = None, altitude_mode: AltitudeMode | None = None, geometry: LinearRing | None = None, kml_coordinates: Coordinates | None = None, **kwargs: Any)[source]

Bases: LineString

Defines a closed line string, typically the outer boundary of a Polygon.

Optionally, a LinearRing can also be used as the inner boundary of a Polygon to create holes in the Polygon. A Polygon can contain multiple <LinearRing> elements used as inner boundaries.

https://developers.google.com/kml/documentation/kmlreference#linearring

property geometry: LinearRing | None

Get the geometry of the LinearRing.

Returns:

  • Optional[geo.LinearRing] (The geometry of the LinearRing,)

  • or None if kml_coordinates is not set or if there is a DimensionError.

class fastkml.geometry.MultiGeometry(*, ns: str | None = None, name_spaces: dict[str, str] | None = None, id: str | None = None, target_id: str | None = None, extrude: bool | None = None, tessellate: bool | None = None, altitude_mode: AltitudeMode | None = None, kml_geometries: Iterable[Point | LineString | Polygon | LinearRing | Self | Track | MultiTrack] | None = None, geometry: MultiPoint | MultiLineString | MultiPolygon | GeometryCollection | None = None, **kwargs: Any)[source]

Bases: _BaseObject

A container for zero or more geometry primitives.

property geometry: MultiPoint | MultiLineString | MultiPolygon | GeometryCollection | None

Return the geometry of the MultiGeometry.

kml_geometries: list[Point | LineString | Polygon | LinearRing | Self | Track | MultiTrack]
class fastkml.geometry.OuterBoundaryIs(*, ns: str | None = None, name_spaces: dict[str, str] | None = None, geometry: LinearRing | None = None, kml_geometry: LinearRing | None = None, **kwargs: Any)[source]

Bases: BoundaryIs

Represents the outer boundary of a polygon in KML.

classmethod get_tag_name() str[source]

Get the tag name for the OuterBoundaryIs object.

Returns:

The tag name.

Return type:

str

class fastkml.geometry.Point(*, ns: str | None = None, name_spaces: dict[str, str] | None = None, id: str | None = None, target_id: str | None = None, extrude: bool | None = None, altitude_mode: AltitudeMode | None = None, geometry: Point | None = None, kml_coordinates: Coordinates | None = None, **kwargs: Any)[source]

Bases: _Geometry

A geographic location defined by longitude, latitude, and (optional) altitude.

When a Point is contained by a Placemark, the point itself determines the position of the Placemark’s name and icon. When a Point is extruded, it is connected to the ground with a line. This “tether” uses the current LineStyle.

https://developers.google.com/kml/documentation/kmlreference#point

extrude: bool | None
property geometry: Point | None

Get the geometry object of the Point.

Returns:

  • Optional[geo.Point] (The geometry object of the Point,)

  • or None if it doesn’t exist.

kml_coordinates: Coordinates | None
class fastkml.geometry.Polygon(*, ns: str | None = None, name_spaces: dict[str, str] | None = None, id: str | None = None, target_id: str | None = None, extrude: bool | None = None, tessellate: bool | None = None, altitude_mode: AltitudeMode | None = None, outer_boundary: OuterBoundaryIs | None = None, inner_boundaries: Iterable[InnerBoundaryIs] | None = None, geometry: Polygon | None = None, **kwargs: Any)[source]

Bases: _Geometry

A Polygon is defined by an outer boundary and 0 or more inner boundaries.

The boundaries, in turn, are defined by LinearRings. When a Polygon is extruded, its boundaries are connected to the ground to form additional polygons, which gives the appearance of a building or a box. Extruded Polygons use <PolyStyle> for their color, color mode, and fill.

The <coordinates> for polygons must be specified in counterclockwise order.

The outer boundary is represented by the outer_boundary_is attribute, which is an instance of the OuterBoundaryIs class. The inner boundaries are represented by the inner_boundary_is attribute, which is an instance of the InnerBoundaryIs class.

The geometry property returns a geo.Polygon object representing the geometry of the Polygon.

Example usage:

polygon = Polygon(outer_boundary_is=outer_boundary,
    inner_boundary_is=inner_boundary)
print(polygon.geometry)

https://developers.google.com/kml/documentation/kmlreference#polygon

extrude: bool | None
property geometry: Polygon | None

Get the geometry object representing the geometry of the Polygon.

Returns:

The geometry object representing the geometry of the Polygon.

Return type:

Optional[geo.Polygon]

inner_boundaries: list[InnerBoundaryIs]
outer_boundary: OuterBoundaryIs | None
tessellate: bool | None
fastkml.geometry.create_kml_geometry(geometry: GeoType | GeoCollectionType, *, ns: str | None = None, name_spaces: dict[str, str] | None = None, id: str | None = None, target_id: str | None = None, extrude: bool | None = None, tessellate: bool | None = None, altitude_mode: AltitudeMode | None = None) Point | LineString | Polygon | LinearRing | MultiGeometry | Track | MultiTrack[source]

Create a KML geometry from a geometry object.

Args:

geometry: Geometry object. ns: Namespace of the object name_spaces: Name spaces of the object id: Id of the object target_id: Target id of the object extrude: Specifies whether to connect the feature to the ground with a line. tessellate: Specifies whether to allow the LineString to follow the terrain. altitude_mode: Specifies how altitude components in the <coordinates>

element are interpreted.

Returns:

KML geometry object.

fastkml.geometry.create_multigeometry(geometries: Sequence[Polygon | LineString | LinearRing | Point | MultiPoint | MultiLineString | MultiPolygon | GeometryCollection]) MultiPoint | MultiLineString | MultiPolygon | GeometryCollection | None[source]

Create a MultiGeometry from a sequence of geometries.

Args:

geometries: Sequence of geometries.

Returns:

MultiGeometry

fastkml.gx.data

GX SimpleArrayData and SimpleArrayField Extension.

class fastkml.gx.data.SimpleArrayData(ns: str | None = None, name_spaces: dict[str, str] | None = None, id: str | None = None, target_id: str | None = None, name: str | None = None, data: Iterable[str] | None = None, **kwargs: Any)[source]

Bases: _BaseObject

A SimpleArrayData element.

This element is used to define an array of string values. It is used in conjunction with the gx:SimpleArrayField element to specify how the array values are to be displayed.

data: list[str | None]
name: str | None
class fastkml.gx.data.SimpleArrayField(ns: str | None = None, name_spaces: dict[str, str] | None = None, name: str | None = None, type_: DataType | None = None, display_name: str | None = None, **kwargs: Any)[source]

Bases: _XMLObject

A SimpleArrayField always has both name and type attributes.

The declaration of the custom field, must specify both the type and the name of this field. If either the type or the name is omitted, the field is ignored.

The type can be one of the following:
  • string

  • int

  • uint

  • short

  • ushort

  • float

  • double

  • bool

The displayName, if any, to be used when the field name is displayed to the Google Earth user.

display_name: str | None
name: str | None
type_: DataType | None

fastkml.gx.track

GX Track Extension.

class fastkml.gx.track.Angle(heading: float = 0.0, tilt: float = 0.0, roll: float = 0.0)[source]

Bases: object

The gx:angles element specifies the heading, tilt, and roll.

The angles are specified in degrees, and the default values are 0 (heading and tilt) and 0 (roll). The angles are specified in the following order: heading, tilt, roll.

property coords: tuple[float, float] | tuple[float, float, float]

Get the coordinates of the angle.

Returns:

The coordinates of the angle.

Return type:

PointType

heading: float = 0.0
roll: float = 0.0
tilt: float = 0.0
class fastkml.gx.track.MultiTrack(*, ns: str | None = None, name_spaces: dict[str, str] | None = None, id: str | None = None, target_id: str | None = None, altitude_mode: AltitudeMode | None = None, tracks: Iterable[Track] | None = None, interpolate: bool | None = None, **kwargs: Any)[source]

Bases: _Geometry

A MultiTrack is a collection of tracks.

A multi-track element is used to combine multiple track elements into a single conceptual unit. For example, suppose you collect GPS data for a day’s bike ride that includes several rest stops and a stop for lunch. Because of the interruptions in time, one bike ride might appear as four different tracks when the times and positions are plotted. Grouping these <gx:Track> elements into one <gx:MultiTrack> container causes them to be displayed in Google Earth as sections of a single path. When the icon reaches the end of one segment, it moves to the beginning of the next segment. The <gx:interpolate> element specifies whether to stop at the end of one track and jump immediately to the start of the next one, or to interpolate the missing values between the two tracks.

property geometry: MultiLineString | None

Get the geometry of the gx object.

Returns:

Optional[geo.MultiLineString]

Return type:

The geometry of the gx object.

tracks: list[Track]
class fastkml.gx.track.Track(*, ns: str | None = None, name_spaces: dict[str, str] | None = None, id: str | None = None, target_id: str | None = None, altitude_mode: AltitudeMode | None = None, track_items: Iterable[TrackItem] | None = None, whens: Iterable[KmlDateTime] | None = None, coords: Iterable[tuple[float, float] | tuple[float, float, float]] | None = None, angles: Iterable[tuple[float, float] | tuple[float, float, float]] | None = None, extended_data: ExtendedData | None = None, **kwargs: Any)[source]

Bases: _Geometry

A track describes how an object moves through the world over a given time period.

This feature allows you to create one visible object in Google Earth (either a Point icon or a Model) that encodes multiple positions for the same object for multiple times. In Google Earth, the time slider allows the user to move the view through time, which animates the position of the object.

Tracks are a more efficient mechanism for associating time data with visible Features, since you create only one Feature, which can be associated with multiple time elements as the object moves through space.

https://developers.google.com/kml/documentation/kmlreference#gxtrack

property angles: tuple[tuple[float, float] | tuple[float, float, float], ...]

Get the angles of the track items.

Returns:

The angles of the track items.

Return type:

Tuple[Angle]

property coords: tuple[tuple[float, float] | tuple[float, float, float], ...]

Get the coordinates of the track items.

Returns:

The coordinates of the track items.

Return type:

Tuple[PointType]

extended_data: ExtendedData | None
property geometry: LineString | None

Get the geometry of the track.

Returns:

The geometry of the track.

Return type:

Optional[geo.LineString]

track_items: list[TrackItem]
property whens: tuple[KmlDateTime, ...]

Get the timestamps of the track items.

Returns:

The timestamps of the track items.

Return type:

Tuple[KmlDateTime]

class fastkml.gx.track.TrackItem(when: KmlDateTime, coord: Point, angle: Angle | None = None)[source]

Bases: object

A track item describes an objects position and heading at a specific time.

angle: Angle | None = None
coord: Point
when: KmlDateTime
fastkml.gx.track.track_items_to_geometry(track_items: Iterable[TrackItem]) LineString[source]

Convert a sequence of TrackItems to a LineString geometry.

Args:

track_itemsIterable[TrackItem]

A sequence of TrackItems.

Returns:

geo.LineString

A LineString geometry representing the track.

fastkml.gx.track.tracks_to_geometry(tracks: Iterable[Track]) MultiLineString[source]

Convert a collection of tracks to a MultiLineString geometry.

Args:

tracksIterable[Track]

A collection of tracks.

Returns:

geo.MultiLineString

A MultiLineString geometry representing the tracks.

fastkml.mixins

Mixins for the KML classes.

class fastkml.mixins.TimeMixin[source]

Bases: object

Mixin for classes that have a time element.

property begin: KmlDateTime | None

Return the start time of a time span.

property end: KmlDateTime | None

Return the end time of a time span.

property time_stamp: KmlDateTime | None

Return the timestamp.

times: TimeSpan | TimeStamp | None = None

fastkml.model

Model element.

The Model element defines a 3D model that is attached to a Placemark.

https://developers.google.com/kml/documentation/models https://developers.google.com/kml/documentation/kmlreference#model

class fastkml.model.Alias(ns: str | None = None, name_spaces: dict[str, str] | None = None, id: str | None = None, target_id: str | None = None, target_href: str | None = None, source_href: str | None = None, **kwargs: Any)[source]

Bases: _BaseObject

Represents an alias in KML.

source_href: str | None
target_href: str | None
class fastkml.model.Location(ns: str | None = None, name_spaces: dict[str, str] | None = None, id: str | None = None, target_id: str | None = None, altitude: float | None = None, latitude: float | None = None, longitude: float | None = None, **kwargs: Any)[source]

Bases: _BaseObject

Represents a location in KML.

altitude: float | None
property geometry: Point | None

Return a Point representation of the geometry.

latitude: float | None
longitude: float | None
class fastkml.model.Model(ns: str | None = None, name_spaces: dict[str, str] | None = None, id: str | None = None, target_id: str | None = None, altitude_mode: AltitudeMode | None = None, location: Location | None = None, orientation: Orientation | None = None, scale: Scale | None = None, link: Link | None = None, resource_map: ResourceMap | None = None, **kwargs: Any)[source]

Bases: _BaseObject

Represents a model in KML.

altitude_mode: AltitudeMode | None
property geometry: Point | None

Return a Point representation of the geometry.

location: Location | None
orientation: Orientation | None
resource_map: ResourceMap | None
scale: Scale | None
class fastkml.model.Orientation(ns: str | None = None, name_spaces: dict[str, str] | None = None, id: str | None = None, target_id: str | None = None, heading: float | None = None, tilt: float | None = None, roll: float | None = None, **kwargs: Any)[source]

Bases: _BaseObject

Represents an orientation in KML.

heading: float | None
roll: float | None
tilt: float | None
class fastkml.model.ResourceMap(ns: str | None = None, name_spaces: dict[str, str] | None = None, id: str | None = None, target_id: str | None = None, aliases: Iterable[Alias] | None = None, **kwargs: Any)[source]

Bases: _BaseObject

Represents a resource map in KML.

aliases: list[Alias]
class fastkml.model.Scale(ns: str | None = None, name_spaces: dict[str, str] | None = None, id: str | None = None, target_id: str | None = None, x: float | None = None, y: float | None = None, z: float | None = None, **kwargs: Any)[source]

Bases: _BaseObject

Represents a scale in KML.

x: float | None
y: float | None
z: float | None

fastkml.overlays

Overlays.

class fastkml.overlays.GroundOverlay(ns: str | None = None, name_spaces: dict[str, str] | None = None, id: str | None = None, target_id: str | None = None, name: str | None = None, visibility: bool | None = None, isopen: bool | None = None, atom_link: Link | None = None, atom_author: Author | None = None, address: str | None = None, phone_number: str | None = None, snippet: Snippet | None = None, description: str | None = None, view: Camera | LookAt | None = None, times: TimeSpan | TimeStamp | None = None, style_url: StyleUrl | None = None, styles: Iterable[Style | StyleMap] | None = None, region: Region | None = None, extended_data: ExtendedData | None = None, color: str | None = None, draw_order: int | None = None, icon: Icon | None = None, altitude: float | None = None, altitude_mode: AltitudeMode | None = None, lat_lon_box: LatLonBox | None = None, **kwargs: Any)[source]

Bases: _Overlay

Draw 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.

https://developers.google.com/kml/documentation/kmlreference#groundoverlay

altitude: float | None
altitude_mode: AltitudeMode | None
lat_lon_box: LatLonBox | None
class fastkml.overlays.ImagePyramid(ns: str | None = None, name_spaces: dict[str, str] | None = None, id: str | None = None, target_id: str | None = None, tile_size: int | None = None, max_width: int | None = None, max_height: int | None = None, grid_origin: GridOrigin | None = None, **kwargs: Any)[source]

Bases: _BaseObject

For very large images, you’ll need to construct an image pyramid.

An ImagePyramid is a hierarchical set of images, each of which is an increasingly lower resolution version of the original image. Each image in the pyramid is subdivided into tiles, so that only the portions in view need to be loaded. Google Earth calculates the current viewpoint and loads the tiles that are appropriate to the user’s distance from the image. As the viewpoint moves closer to the PhotoOverlay, Google Earth loads higher resolution tiles. Since all the pixels in the original image can’t be viewed on the screen at once, this preprocessing allows Google Earth to achieve maximum performance because it loads only the portions of the image that are in view, and only the pixel details that can be discerned by the user at the current viewpoint.

When you specify an image pyramid, you also need to modify the <href> in the <Icon> element to include specifications for which tiles to load.

https://developers.google.com/kml/documentation/kmlreference#imagepyramid

grid_origin: GridOrigin | None
max_height: int | None
max_width: int | None
tile_size: int | None
class fastkml.overlays.LatLonBox(ns: str | None = None, name_spaces: dict[str, str] | None = None, id: str | None = None, target_id: str | None = None, north: float | None = None, south: float | None = None, east: float | None = None, west: float | None = None, rotation: float | None = None, **kwargs: Any)[source]

Bases: _BaseObject

Specifies the top, bottom, right, and left sides of a bounding box for an overlay.

Also, optionally the rotation of the overlay.

<north> Specifies the latitude of the north edge of the bounding box, in decimal degrees from 0 to ±90. <south> Specifies the latitude of the south edge of the bounding box, in decimal degrees from 0 to ±90. <east> 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> 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> 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.

https://developers.google.com/kml/documentation/kmlreference#latlonbox

east: float | None
north: float | None
rotation: float | None
south: float | None
west: float | None
class fastkml.overlays.OverlayXY(ns: str | None = None, name_spaces: dict[str, str] | None = None, x: float | None = None, y: float | None = None, x_units: Units | None = None, y_units: Units | None = None, **kwargs: Any)[source]

Bases: _XY

Specifies the placement of the overlay on the screen.

classmethod get_tag_name() str[source]

Return the tag name.

class fastkml.overlays.PhotoOverlay(ns: str | None = None, name_spaces: dict[str, str] | None = None, id: str | None = None, target_id: str | None = None, name: str | None = None, visibility: bool | None = None, isopen: bool | None = None, atom_link: Link | None = None, atom_author: Author | None = None, address: str | None = None, phone_number: str | None = None, snippet: Snippet | None = None, description: str | None = None, view: Camera | LookAt | None = None, times: TimeSpan | TimeStamp | None = None, style_url: StyleUrl | None = None, styles: Iterable[Style | StyleMap] | None = None, region: Region | None = None, extended_data: ExtendedData | None = None, color: str | None = None, draw_order: int | None = None, icon: Icon | None = None, rotation: float | None = None, view_volume: ViewVolume | None = None, image_pyramid: ImagePyramid | None = None, point: Point | None = None, shape: Shape | None = None, **kwargs: Any)[source]

Bases: _Overlay

PhotoOverlays are photographs that are directly embedded in the Earth’s landscape.

The <PhotoOverlay> element allows you to geographically locate a photograph on the Earth and to specify viewing parameters for this PhotoOverlay. The PhotoOverlay can be a simple 2D rectangle, a partial or full cylinder, or a sphere (for spherical panoramas). The overlay is placed at the specified location and oriented toward the viewpoint.

Because <PhotoOverlay> is derived from <Feature>, it can contain one of the two elements derived from <AbstractView>—either <Camera> or <LookAt>. The Camera (or LookAt) specifies a viewpoint and a viewing direction (also referred to as a view vector). The PhotoOverlay is positioned in relation to the viewpoint. Specifically, the plane of a 2D rectangular image is orthogonal (at right angles to) the view vector. The normal of this plane—that is, its front, which is the part with the photo—is oriented toward the viewpoint.

The URL for the PhotoOverlay image is specified in the <Icon> tag, which is inherited from <Overlay>. The <Icon> tag must contain an <href> element that specifies the image file to use for the PhotoOverlay. In the case of a very large image, the <href> is a special URL that indexes into a pyramid of images of varying resolutions (see ImagePyramid).

https://developers.google.com/kml/documentation/kmlreference#photooverlay

image_pyramid: ImagePyramid | None
point: Point | None
rotation: float | None
shape: Shape | None
view_volume: ViewVolume | None
class fastkml.overlays.RotationXY(ns: str | None = None, name_spaces: dict[str, str] | None = None, x: float | None = None, y: float | None = None, x_units: Units | None = None, y_units: Units | None = None, **kwargs: Any)[source]

Bases: _XY

Specifies the rotation of the overlay on the screen.

classmethod get_tag_name() str[source]

Return the tag name.

class fastkml.overlays.ScreenOverlay(ns: str | None = None, name_spaces: dict[str, str] | None = None, id: str | None = None, target_id: str | None = None, name: str | None = None, visibility: bool | None = None, isopen: bool | None = None, atom_link: Link | None = None, atom_author: Author | None = None, address: str | None = None, phone_number: str | None = None, snippet: Snippet | None = None, description: str | None = None, view: Camera | LookAt | None = None, times: TimeSpan | TimeStamp | None = None, style_url: StyleUrl | None = None, styles: Iterable[Style | StyleMap] | None = None, region: Region | None = None, extended_data: ExtendedData | None = None, color: str | None = None, draw_order: int | None = None, icon: Icon | None = None, overlay_xy: OverlayXY | None = None, screen_xy: ScreenXY | None = None, rotation_xy: RotationXY | None = None, size: Size | None = None, rotation: float | None = None, **kwargs: Any)[source]

Bases: _Overlay

A ScreenOverlay draws an image overlay fixed to the screen.

This element draws an image overlay fixed to the screen. Sample uses include watermarking the map with an image, such as a company logo, or adding a heads-up display (HUD) to show real-time information.

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.

https://developers.google.com/kml/documentation/kmlreference#screenoverlay

class fastkml.overlays.ScreenXY(ns: str | None = None, name_spaces: dict[str, str] | None = None, x: float | None = None, y: float | None = None, x_units: Units | None = None, y_units: Units | None = None, **kwargs: Any)[source]

Bases: _XY

Specifies the placement of the overlay on the screen.

classmethod get_tag_name() str[source]

Return the tag name.

class fastkml.overlays.Size(ns: str | None = None, name_spaces: dict[str, str] | None = None, x: float | None = None, y: float | None = None, x_units: Units | None = None, y_units: Units | None = None, **kwargs: Any)[source]

Bases: _XY

Specifies the size of the overlay on the screen.

classmethod get_tag_name() str[source]

Return the tag name.

class fastkml.overlays.ViewVolume(ns: str | None = None, name_spaces: dict[str, str] | None = None, id: str | None = None, target_id: str | None = None, left_fov: float | None = None, right_fov: float | None = None, bottom_fov: float | None = None, top_fov: float | None = None, near: float | None = None, **kwargs: Any)[source]

Bases: _BaseObject

The ViewVolume defines how much of the current scene is visible.

Specifying the field of view is analogous to specifying the lens opening in a physical camera. A small field of view, like a telephoto lens, focuses on a small part of the scene. A large field of view, like a wide-angle lens, focuses on a large part of the scene.

https://developers.google.com/kml/documentation/kmlreference#viewvolume

bottom_fov: float | None
left_fow: float | None
near: float | None
right_fov: float | None
top_fov: float | None

fastkml.styles

KML Styles.

Once you’ve created features within Google Earth and examined the KML code Google Earth generates, you’ll notice how styles are an important part of how your data is displayed.

class fastkml.styles.BalloonStyle(ns: str | None = None, name_spaces: dict[str, str] | None = None, id: str | None = None, target_id: str | None = None, bg_color: str | None = None, text_color: str | None = None, text: str | None = None, display_mode: DisplayMode | None = None, **kwargs: Any)[source]

Bases: _BaseObject

Specifies how the description balloon for placemarks is drawn.

The <bgColor>, if specified, is used as the background color of the balloon.

https://developers.google.com/kml/documentation/kmlreference#balloonstyle

bg_color: str | None
display_mode: DisplayMode | None
text: str | None
text_color: str | None
class fastkml.styles.HotSpot(ns: str | None = None, name_spaces: dict[str, str] | None = None, x: float | None = None, y: float | None = None, xunits: Units | None = None, yunits: Units | None = None, **kwargs: Any)[source]

Bases: _XMLObject

Specifies the position within the Icon that is “anchored” to the <Point>.

x - Either the number of pixels, a fractional component of the icon, or a pixel inset indicating the x component of a point on the icon. y - Either the number of pixels, a fractional component of the icon, or a pixel inset indicating the y component of a point on the icon. xunits - Units in which the x value is specified. A value of fraction indicates the x value is a fraction of the icon. A value of pixels indicates the x value in pixels. A value of insetPixels indicates the indent from the right edge of the icon. yunits - Units in which the y value is specified.

https://developers.google.com/kml/documentation/kmlreference#hotspot

classmethod get_tag_name() str[source]

Return the tag name.

x: float | None
xunits: Units | None
y: float | None
yunits: Units | None
class fastkml.styles.IconStyle(ns: str | None = None, name_spaces: dict[str, str] | None = None, id: str | None = None, target_id: str | None = None, color: str | None = None, color_mode: ColorMode | None = None, scale: float | None = None, heading: float | None = None, icon: Icon | None = None, icon_href: str | None = None, hot_spot: HotSpot | None = None, **kwargs: Any)[source]

Bases: _ColorStyle

Specifies how icons for point Placemarks are drawn.

The <Icon> element specifies the icon image. The <scale> element specifies the x, y scaling of the icon. The color specified in the <color> element of <IconStyle> is blended with the color of the <Icon>.

https://developers.google.com/kml/documentation/kmlreference#iconstyle

heading: float | None
hot_spot: HotSpot | None
icon: Icon | None
property icon_href: str | None

Return the icon href.

scale: float | None
class fastkml.styles.LabelStyle(ns: str | None = None, name_spaces: dict[str, str] | None = None, id: str | None = None, target_id: str | None = None, color: str | None = None, color_mode: ColorMode | None = None, scale: float | None = None, **kwargs: Any)[source]

Bases: _ColorStyle

Specifies how the <name> of a Feature is drawn in the 3D viewer.

A custom color, color mode, and scale for the label (name) can be specified.

https://developers.google.com/kml/documentation/kmlreference#labelstyle

scale: float | None
class fastkml.styles.LineStyle(ns: str | None = None, name_spaces: dict[str, str] | None = None, id: str | None = None, target_id: str | None = None, color: str | None = None, color_mode: ColorMode | None = None, width: float | None = None, **kwargs: Any)[source]

Bases: _ColorStyle

The drawing style (color, color mode, and line width) for all line geometry.

Line geometry includes the outlines of outlined polygons and the extruded “tether” of Placemark icons (if extrusion is enabled). https://developers.google.com/kml/documentation/kmlreference#linestyle

width: float | None
class fastkml.styles.Pair(ns: str | None = None, name_spaces: dict[str, str] | None = None, id: str | None = None, target_id: str | None = None, key: PairKey | None = None, style: StyleUrl | Style | None = None, **kwargs: Any)[source]

Bases: _BaseObject

Stylemap pair.

Defines a key/value pair that maps a mode (normal or highlight) to the predefined <styleUrl>. <Pair> contains two elements (both are required):

<key>, which identifies the key <styleUrl> or <Style>, which references the style. In <styleUrl>, for referenced style elements that are local to the KML document, a simple # referencing is used. For styles that are contained in external files, use a full URL along with # referencing.

https://developers.google.com/kml/documentation/kmlreference#stylemap

key: PairKey | None
style: StyleUrl | Style | None
class fastkml.styles.PolyStyle(ns: str | None = None, name_spaces: dict[str, str] | None = None, id: str | None = None, target_id: str | None = None, color: str | None = None, color_mode: ColorMode | None = None, fill: bool | None = None, outline: bool | None = None, **kwargs: Any)[source]

Bases: _ColorStyle

Drawing style for polygons.

Specifies the drawing style for all polygons, including polygon extrusions (which look like the walls of buildings) and line extrusions (which look like solid fences).

https://developers.google.com/kml/documentation/kmlreference#polystyle

fill: bool | None
outline: bool | None
class fastkml.styles.Style(ns: str | None = None, name_spaces: dict[str, str] | None = None, id: str | None = None, target_id: str | None = None, styles: Iterable[BalloonStyle | IconStyle | LabelStyle | LineStyle | PolyStyle] | None = None, **kwargs: Any)[source]

Bases: _StyleSelector

A Style defines an addressable style group.

It can be referenced by StyleMaps and Features. Styles affect how Geometry is presented in the 3D viewer and how Features appear in the Places panel of the List view. Shared styles are collected in a <Document> and must have an id defined for them so that they can be referenced by the individual Features that use them.

https://developers.google.com/kml/documentation/kmlreference#style

class fastkml.styles.StyleMap(ns: str | None = None, name_spaces: dict[str, str] | None = None, id: str | None = None, target_id: str | None = None, pairs: Iterable[Pair] | None = None, **kwargs: Any)[source]

Bases: _StyleSelector

A <StyleMap> maps between two different Styles.

Typically a <StyleMap> element is used to provide separate normal and highlighted styles for a placemark, so that the highlighted version appears when the user mouses over the icon in Google Earth.

https://developers.google.com/kml/documentation/kmlreference#stylemap

property highlight: StyleUrl | Style | None

Return the highlight style associated with this StyleMap.

Returns:

  • The highlight style, which can be either a StyleUrl or a Style object.

  • If no highlight style is found, None is returned.

property normal: StyleUrl | Style | None

Get the normal style for the feature.

Return type:

The normal style for the feature, if available. Otherwise, returns None.

pairs: list[Pair]
class fastkml.styles.StyleUrl(ns: str | None = None, name_spaces: dict[str, str] | None = None, url: str | None = None, **kwargs: Any)[source]

Bases: _XMLObject

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.

https://developers.google.com/kml/documentation/kmlreference#styleurl

classmethod get_tag_name() str[source]

Return the tag name.

url: str | None

fastkml.times

Date and time handling in KML.

Any Feature in KML can have time data associated with it. This time data has the effect of restricting the visibility of the data set to a given time period or point in time.

https://developers.google.com/kml/documentation/time

class fastkml.times.KmlDateTime(dt: date | datetime, resolution: DateTimeResolution | None = None)[source]

Bases: object

A KML DateTime object.

This class is used to parse and format KML DateTime objects.

A KML DateTime object is a string that conforms to the ISO 8601 standard for date and time representation. The following formats are supported:

  • yyyy-mm-ddThh:mm:sszzzzzz

  • yyyy-mm-ddThh:mm:ss

  • yyyy-mm-dd

  • yyyy-mm

  • yyyy

The T is the separator between the date and the time, and the time zone is either Z (for UTC) or zzzzzz, which represents ±hh:mm in relation to UTC. Additionally, the value can be expressed as a date only.

The precision of the DateTime is dictated by the DateTime value which can be one of the following:

  • dateTime gives second resolution

  • date gives day resolution

  • gYearMonth gives month resolution

  • gYear gives year resolution

The KmlDateTime class can be used to parse a KML DateTime string into a Python datetime object, or to format a Python datetime object into a KML DateTime string.

The KmlDateTime class is used by the TimeStamp and TimeSpan classes.

classmethod get_ns_id() str[source]

Return the namespace ID.

classmethod parse(datestr: str) KmlDateTime | None[source]

Parse a KML DateTime string into a KmlDateTime object.

class fastkml.times.TimeSpan(ns: str | None = None, name_spaces: dict[str, str] | None = None, id: str | None = None, target_id: str | None = None, begin: KmlDateTime | None = None, end: KmlDateTime | None = None, **kwargs: Any)[source]

Bases: _TimePrimitive

Represents an extent in time bounded by begin and end dateTimes.

https://developers.google.com/kml/documentation/kmlreference#timespan

class fastkml.times.TimeStamp(ns: str | None = None, name_spaces: dict[str, str] | None = None, id: str | None = None, target_id: str | None = None, timestamp: KmlDateTime | None = None, **kwargs: Any)[source]

Bases: _TimePrimitive

Represents a single moment in time.

https://developers.google.com/kml/documentation/kmlreference#timestamp

fastkml.types

Types for fastkml.

class fastkml.types.Element(*args, **kwargs)[source]

Bases: Protocol

Protocol for Element.

append(element: Element) None[source]

Append an element to the current element.

find(tag: str) Element | None[source]

Find the first element with the given tag.

findall(tag: str) Iterable[Element][source]

Find all elements with the given tag.

get(tag: str) str[source]

Get the value of the tag.

remove(element: Element) None[source]

Remove an element from the current element.

set(tag: str, value: str) None[source]

Set the value of the tag.

tag: str
text: str

fastkml.utils

Fastkml utility functions.

fastkml.utils.find(obj: object, *, of_type: type[object] | tuple[type[object], ...] | None = None, **kwargs: Any) object | None[source]

Find the first instance of a given type in a given object.

Args:

obj: The object to search. of_type: The type(s) to search for or None for any type. **kwargs: Attributes of the object to match.

Returns:

The first instance of the given type in the given object or None if not found.

fastkml.utils.find_all(obj: object, *, of_type: type[object] | tuple[type[object], ...] | None = None, **kwargs: Any) Generator[object, None, None][source]

Find all instances of a given type with attributes matching the kwargs.

Args:

obj: The object to search. of_type: The type(s) to search for or None for any type. **kwargs: Attributes of the object to match.

Returns:

An iterable of all instances of the given type in the given object.

fastkml.utils.has_attribute_values(obj: object, **kwargs: Any) bool[source]

Check if an object has all of the given attribute values.

Args:

obj: The object to check. **kwargs: Attributes of the object to match.

Returns:

True if the object has the given attribute values, False otherwise.

fastkml.validator

Validate KML files against the XML schema.

fastkml.validator.get_schema_parser(schema: Path | None = None) etree.XMLSchema[source]

Parse the XML schema.

Args:

schema: The path to the XML schema file.

Returns:

The parsed XML schema.

To clear the cache call get_schema_parser.cache_clear().

fastkml.validator.validate(*, schema: Path | None = None, element: Element | None = None, file_to_validate: Path | None = None) bool | None[source]

Validate a KML file against the XML schema.

Args:

schema: The path to the XML schema file. element: The element to validate. file_to_validate: The file to validate.

Returns:

True if the file or element is valid. Raises an AssertionError if validation fails. Returns None if the schema parser is unavailable.

fastkml.views

KML Views.

class fastkml.views.Camera(ns: str | None = None, name_spaces: dict[str, str] | None = None, id: str | None = None, target_id: str | None = None, longitude: float | None = None, latitude: float | None = None, altitude: float | None = None, heading: float | None = None, tilt: float | None = None, roll: float | None = None, altitude_mode: AltitudeMode | None = None, **kwargs: Any)[source]

Bases: _AbstractView

Defines the virtual camera that views the scene.

This element defines the position of the camera relative to the Earth’s surface as well as the viewing direction of the camera. The camera position is defined by <longitude>, <latitude>, <altitude>, and either <altitudeMode> or <gx:altitudeMode>. The viewing direction of the camera is defined by <heading>, <tilt>, and <roll>. <Camera> can be a child element of any Feature or of <NetworkLinkControl>. A parent element cannot contain both a <Camera> and a <LookAt> at the same time.

<Camera> provides full six-degrees-of-freedom control over the view, so you can position the Camera in space and then rotate it around the X, Y, and Z axes. Most importantly, you can tilt the camera view so that you’re looking above the horizon into the sky.

<Camera> can also contain a TimePrimitive (<gx:TimeSpan> or <gx:TimeStamp>). Time values in Camera affect historical imagery, sunlight, and the display of time-stamped features. For more information, read Time with AbstractViews in the Time and Animation chapter of the Developer’s Guide.

https://developers.google.com/kml/documentation/kmlreference#camera

roll: float | None
class fastkml.views.LatLonAltBox(ns: str | None = None, name_spaces: dict[str, str] | None = None, id: str | None = None, target_id: str | None = None, north: float | None = None, south: float | None = None, east: float | None = None, west: float | None = None, min_altitude: float | None = None, max_altitude: float | None = None, altitude_mode: AltitudeMode | None = None, **kwargs: Any)[source]

Bases: _BaseObject

A bounding box defined by geographic coordinates and altitudes.

https://developers.google.com/kml/documentation/kmlreference#latlonaltbox

altitude_mode: AltitudeMode | None
east: float | None
max_altitude: float | None
min_altitude: float | None
north: float | None
south: float | None
west: float | None
class fastkml.views.Lod(ns: str | None = None, name_spaces: dict[str, str] | None = None, id: str | None = None, target_id: str | None = None, min_lod_pixels: int | None = None, max_lod_pixels: int | None = None, min_fade_extent: int | None = None, max_fade_extent: int | None = None, **kwargs: Any)[source]

Bases: _BaseObject

Lod is an abbreviation for Level of Detail.

<Lod> describes the size of the projected region on the screen that is required in order for the region to be considered “active.” Also specifies the size of the pixel ramp used for fading in (from transparent to opaque) and fading out (from opaque to transparent).

https://developers.google.com/kml/documentation/kmlreference#elements-specific-to-region

max_fade_extent: int | None
max_lod_pixels: int | None
min_fade_extent: int | None
min_lod_pixels: int | None
class fastkml.views.LookAt(ns: str | None = None, name_spaces: dict[str, str] | None = None, id: str | None = None, target_id: str | None = None, longitude: float | None = None, latitude: float | None = None, altitude: float | None = None, heading: float | None = None, tilt: float | None = None, range: float | None = None, altitude_mode: AltitudeMode | None = None, **kwargs: Any)[source]

Bases: _AbstractView

Defines a virtual camera that is associated with any element derived from Feature.

The LookAt element positions the “camera” in relation to the object that is being viewed. In Google Earth, the view “flies to” this LookAt viewpoint when the user double-clicks an item in the Places panel or double-clicks an icon in the 3D viewer.

https://developers.google.com/kml/documentation/kmlreference#lookat

range: float | None
class fastkml.views.Region(ns: str | None = None, name_spaces: dict[str, str] | None = None, id: str | None = None, target_id: str | None = None, lat_lon_alt_box: LatLonAltBox | None = None, lod: Lod | None = None, **kwargs: Any)[source]

Bases: _BaseObject

A region contains a bounding box that describes an area of interest.

In addition, a Region contains an LOD (level of detail) extent (<Lod>), which is a pair of projected coordinate bounding boxes that describe the area that should be loaded in the viewport corresponding to a given level of detail.

https://developers.google.com/kml/documentation/kmlreference#region

lat_lon_alt_box: LatLonAltBox | None
lod: Lod | None