Models
KML ORM provides Django-style model classes for representing different types of KML elements.
Base Element
Base classes for all KML elements.
This module provides the foundational KMLElement class that all other KML element types inherit from, establishing the common interface and Django-style ORM patterns.
- class kmlorm.models.base.KMLElementMeta(name, bases, namespace, **kwargs)[source]
Bases:
ABCMetaMetaclass for KML elements that sets up the manager.
- class kmlorm.models.base.KMLElement(element_id=None, name=None, description=None, visibility=True, **kwargs)[source]
Bases:
ABCBase class for all KML elements.
Provides common attributes and methods shared by all KML element types including Placemark, Folder, Path, and Polygon. This class establishes the Django-style ORM interface pattern.
-
objects:
KMLManager
- __init__(element_id=None, name=None, description=None, visibility=True, **kwargs)[source]
Initialize a KML element with common attributes.
- __str__()[source]
String representation of the KML element.
Returns the name if available, otherwise the class name and id.
- Return type:
- property parent: KMLElement | None
Get the parent container of this element.
- Returns:
The parent KML element (usually a Folder) or None if root-level
- to_dict()[source]
Convert the KML element to a dictionary representation.
- update(**kwargs)[source]
Update multiple attributes at once.
- copy()[source]
Create a copy of this KML element.
- Return type:
KMLElement- Returns:
A new instance with the same attributes but no parent reference
- validate()[source]
Validate the KML element’s data.
This base implementation performs basic validation. Subclasses should override this method to add specific validation logic.
- Return type:
- Returns:
True if validation passes
- Raises:
KMLValidationError – If validation fails
-
objects:
Placemark
Represents point locations with coordinates and metadata.
Placemark model for KML point locations.
This module implements the Placemark class for representing point locations with coordinates and extended attributes from KML files.
- class kmlorm.models.placemark.Placemark(point=None, multigeometry=None, address=None, phone_number=None, snippet=None, style_url=None, extended_data=None, **kwargs)[source]
Bases:
KMLElementRepresents a KML Placemark (point location).
Placemarks are the most common KML elements, representing specific geographic locations with coordinates and optional metadata like addresses, phone numbers, and extended data.
-
objects:
PlacemarkManager= <kmlorm.core.managers.KMLManager object>
- __init__(point=None, multigeometry=None, address=None, phone_number=None, snippet=None, style_url=None, extended_data=None, **kwargs)[source]
Initialize a Placemark with location and metadata.
- Parameters:
point (
Optional[Point]) – Point object containing geometry (for direct Point Placemarks)multigeometry (
Optional[MultiGeometry]) – MultiGeometry object (for MultiGeometry Placemarks)address (
Optional[str]) – Street address or location descriptionstyle_url (
Optional[str]) – Reference to KML style definitionextended_data (
Optional[Dict[str,Any]]) – Dictionary of additional key-value data**kwargs (
Any) – Additional base element attributes (id, name, etc.)
-
point:
Optional[Point]
-
multigeometry:
Optional[MultiGeometry]
- __str__()[source]
String representation of the Placemark.
Returns name if available, otherwise address, otherwise coordinates.
- Return type:
- property coordinates: Coordinate | None
Get coordinates from the point.
- property has_coordinates: bool
Check if placemark has valid coordinates.
- to_dict()[source]
Convert placemark to dictionary representation.
- get_coordinates()[source]
Return the coordinate representation of this placemark.
This method satisfies the HasCoordinates protocol, allowing Placemark objects to be used directly in spatial calculations.
- Return type:
Optional[Coordinate]- Returns:
The Coordinate object from the point, or None if no point/coordinates exist
- distance_to(other, unit=None)[source]
Calculate distance to another spatial object.
- Parameters:
- Return type:
- Returns:
Distance in specified units, or None if this placemark or target has no coordinates
Examples
>>> placemark1 = Placemark(name="NYC", coordinates=(-74.006, 40.7128)) >>> placemark2 = Placemark(name="London", coordinates=(-0.1276, 51.5074)) >>> distance = placemark1.distance_to(placemark2) >>> print(f"Distance: {distance:.1f} km")
>>> # Different units >>> from kmlorm.spatial import DistanceUnit >>> distance_miles = placemark1.distance_to(placemark2, unit=DistanceUnit.MILES)
>>> # Works with Point and Coordinate objects too >>> from kmlorm.models.point import Point, Coordinate >>> point = Point(coordinates=(0, 0)) >>> coord = Coordinate(longitude=1, latitude=1) >>> distance_to_point = placemark1.distance_to(point) >>> distance_to_coord = placemark1.distance_to(coord)
- bearing_to(other)[source]
Calculate bearing to another spatial object.
- Parameters:
other (
Union[Coordinate,Point,Placemark,Tuple[float,float],list]) – Target object with coordinates- Return type:
- Returns:
Initial bearing in degrees (0-360), or None if this placemark or target has no coordinates 0° = North, 90° = East, 180° = South, 270° = West
Examples
>>> placemark1 = Placemark(name="Start", coordinates=(0, 0)) >>> placemark2 = Placemark(name="East", coordinates=(1, 0)) >>> bearing = placemark1.bearing_to(placemark2) # Should be ~90°
- midpoint_to(other)[source]
Find geographic midpoint to another spatial object.
- Parameters:
other (
Union[Coordinate,Point,Placemark,Tuple[float,float],list]) – Target object with coordinates- Return type:
Optional[Coordinate]- Returns:
Coordinate at the midpoint, or None if this placemark or target has no coordinates
Examples
>>> placemark1 = Placemark(name="Start", coordinates=(0, 0)) >>> placemark2 = Placemark(name="End", coordinates=(2, 2)) >>> midpoint = placemark1.midpoint_to(placemark2)
- validate()[source]
Validate the placemark’s data.
- Return type:
- Returns:
True if validation passes
- Raises:
KMLValidationError – If validation fails
-
objects:
Folder
Container for organizing KML elements hierarchically.
Folder model for KML containers.
This module implements the Folder class for organizing and containing other KML elements in a hierarchical structure.
- class kmlorm.models.folder.Folder(**kwargs)[source]
Bases:
KMLElementRepresents a KML Folder (container for organizing elements).
Folders provide hierarchical organization for KML elements, allowing grouping of placemarks, paths, polygons, and nested folders.
-
objects:
FolderManager= <kmlorm.core.managers.KMLManager object>
- __init__(**kwargs)[source]
Initialize a Folder.
- Parameters:
**kwargs (
Any) – Base element attributes (id, name, description, etc.)
- placemarks: PlacemarkRelatedManager
- folders: FolderRelatedManager
- paths: PathRelatedManager
- polygons: PolygonRelatedManager
- points: PointRelatedManager
- to_dict()[source]
Convert folder to dictionary representation.
-
objects:
Path (LineString)
Represents paths and routes as sequences of coordinates.
Path model for KML LineString elements.
This module implements the Path class for representing routes, tracks, and other linear geographic features.
- class kmlorm.models.path.Path(coordinates=None, tessellate=False, altitude_mode='clampToGround', **kwargs)[source]
Bases:
KMLElementRepresents a KML Path (LineString).
Paths represent linear features like routes, tracks, or boundaries defined by a sequence of coordinate points.
- __init__(coordinates=None, tessellate=False, altitude_mode='clampToGround', **kwargs)[source]
Initialize a Path with coordinate points.
- Parameters:
coordinates (
Optional[List[Union[Tuple[float,...],str]]]) – List of coordinate points as tuples or stringstessellate (
bool) – Whether to tessellate the path to follow terrainaltitude_mode (
str) – How altitude is interpreted (“clampToGround”, “relativeToGround”, “absolute”)**kwargs (
Any) – Base element attributes (id, name, description, etc.)
- property point_count: int
Get the number of coordinate points in the path.
- Returns:
Number of coordinate points
- to_dict()[source]
Convert path to dictionary representation.
- objects: KMLManager = <kmlorm.core.managers.KMLManager object>
Polygon
Represents polygon areas with outer and inner boundaries.
Polygon model for KML area elements.
This module implements the Polygon class for representing geographic areas and regions with boundaries.
- class kmlorm.models.polygon.Polygon(outer_boundary=None, inner_boundaries=None, extrude=False, altitude_mode='clampToGround', **kwargs)[source]
Bases:
KMLElementRepresents a KML Polygon.
Polygons represent enclosed geographic areas with an outer boundary and optional inner boundaries (holes).
- __init__(outer_boundary=None, inner_boundaries=None, extrude=False, altitude_mode='clampToGround', **kwargs)[source]
Initialize a Polygon with boundaries.
- Parameters:
outer_boundary (
Optional[List[Union[Tuple[float,...],str]]]) – List of coordinates defining the outer boundaryinner_boundaries (
Optional[List[List[Union[Tuple[float,...],str]]]]) – List of inner boundary coordinate lists (holes)extrude (
bool) – Whether to extrude the polygon to ground levelaltitude_mode (
str) – How altitude is interpreted**kwargs (
Any) – Base element attributes (id, name, description, etc.)
- property boundary_point_count: int
Get the number of points in the outer boundary.
- Returns:
Number of boundary points
- property hole_count: int
Get the number of holes (inner boundaries).
- Returns:
Number of holes
- to_dict()[source]
Convert polygon to dictionary representation.
- objects: KMLManager = <kmlorm.core.managers.KMLManager object>
Point
Represents standalone Point geometries.
Point model for standalone Point geometries in KML files.
This module defines the Point class for handling standalone Point elements that exist as direct children of Document/Folder elements, separate from Placemarks that contain Point geometries.
- class kmlorm.models.point.Coordinate(longitude, latitude, altitude=0)[source]
Bases:
objectRepresents a geographic coordinate with longitude, latitude, and optional altitude.
- longitude
The longitude of the coordinate.
- Type:
- latitude
The latitude of the coordinate.
- Type:
- altitude
The altitude of the coordinate, if available.
- Type:
Optional[float]
- from_tuple(t
Tuple[float, …]) -> “Coordinate”: Creates a Coordinate instance from a tuple containing longitude, latitude, and optionally altitude.
- from_string(s
str) -> “Coordinate”: Creates a Coordinate instance from a comma-separated string representation of longitude, latitude, and optionally altitude.
-
longitude:
float
-
latitude:
float
-
altitude:
float= 0
- __post_init__()[source]
Post-initialization hook that is automatically called after the dataclass is instantiated. This method triggers validation logic to ensure the object’s state is consistent and valid.
- Return type:
- classmethod from_tuple(t)[source]
Create a Coordinate instance from a tuple of floats.
- Parameters:
t (Tuple[float, ...]) – A tuple containing longitude, latitude, and optionally altitude.
- Returns:
- An instance of Coordinate with the specified longitude, latitude,
and optional altitude.
- Return type:
Coordinate
- Raises:
IndexError – If the tuple does not contain at least two elements.
ValueError – If the tuple elements cannot be converted to float.
- classmethod from_string(s)[source]
Creates a Coordinate instance from a comma-separated string.
- Parameters:
s (str) – A string containing coordinate values separated by commas (e.g., “longitude, latitude, [altitude]”).
- Returns:
An instance of the Coordinate class created from the parsed values.
- Return type:
Coordinate
- Raises:
ValueError – If the string cannot be parsed into valid float values.
- classmethod from_any(value)[source]
Creates a Coordinate instance from various input types.
- Parameters:
value (Union[Tuple[float, ...], str, list, Coordinate]) – The input value to convert. Can be a tuple, list, string, or another Coordinate instance.
- Returns:
A Coordinate instance created from the input value.
- Return type:
Coordinate
- Raises:
TypeError – If the input value is not a tuple, list, string, or Coordinate.
- validate()[source]
Validates the longitude, latitude, and optional altitude values of the point.
- Returns:
True if all coordinate values are valid.
- Return type:
- Raises:
KMLValidationError – If longitude or latitude are not numeric, out of valid range, or if altitude is provided and is not a finite numeric value.
- to_dict()[source]
Convert coordinate to dictionary representation.
- get_coordinates()[source]
Return self as the coordinate representation.
This method satisfies the HasCoordinates protocol, allowing Coordinate objects to be used directly in spatial calculations.
- Return type:
Optional[Coordinate]- Returns:
Self (this Coordinate object)
- distance_to(other, unit=None)[source]
Calculate distance to another spatial object.
- Parameters:
- Return type:
- Returns:
Distance in specified units, or None if target has no coordinates
Examples
>>> coord1 = Coordinate(longitude=-74.006, latitude=40.7128) # NYC >>> coord2 = Coordinate(longitude=-0.1276, latitude=51.5074) # London >>> distance = coord1.distance_to(coord2) >>> print(f"Distance: {distance:.1f} km")
>>> # Different units >>> from kmlorm.spatial import DistanceUnit >>> distance_miles = coord1.distance_to(coord2, unit=DistanceUnit.MILES)
- bearing_to(other)[source]
Calculate bearing to another spatial object.
- Parameters:
other (
Union[Coordinate,Point,Placemark,Tuple[float,float],list]) – Target object with coordinates- Return type:
- Returns:
Initial bearing in degrees (0-360), or None if target has no coordinates 0° = North, 90° = East, 180° = South, 270° = West
Examples
>>> coord1 = Coordinate(longitude=0, latitude=0) >>> coord2 = Coordinate(longitude=1, latitude=0) # Due east >>> bearing = coord1.bearing_to(coord2) >>> print(f"Bearing: {bearing:.1f}°") # Should be ~90°
- midpoint_to(other)[source]
Find geographic midpoint to another spatial object.
- Parameters:
other (
Union[Coordinate,Point,Placemark,Tuple[float,float],list]) – Target object with coordinates- Return type:
Optional[Coordinate]- Returns:
Coordinate at the midpoint, or None if target has no coordinates
Examples
>>> coord1 = Coordinate(longitude=0, latitude=0) >>> coord2 = Coordinate(longitude=2, latitude=2) >>> midpoint = coord1.midpoint_to(coord2) >>> print(f"Midpoint: ({midpoint.longitude}, {midpoint.latitude})")
- __hash__()[source]
Hash for caching support in spatial calculations.
- Return type:
- Returns:
Hash based on longitude, latitude, and altitude
- __init__(longitude, latitude, altitude=0)
- class kmlorm.models.point.Point(**kwargs)[source]
Bases:
KMLElementRepresents a standalone Point geometry in KML.
Points can exist as standalone elements or within other containers. This class handles Points that are direct children of Document/Folder elements, separate from Points that exist within Placemarks.
- coordinates
Tuple of (longitude, latitude, altitude)
- extrude
Whether the point is extruded to ground
- altitude_mode
How altitude is interpreted
- tessellate
Whether lines are tessellated
- __init__(**kwargs)[source]
Initialize a Point with coordinates and properties.
- property coordinates: Coordinate | None
Get coordinates tuple.
- validate()[source]
Validate the point’s coordinates.
- to_dict()[source]
Convert point to dictionary representation.
- get_coordinates()[source]
Return the coordinate representation of this point.
This method satisfies the HasCoordinates protocol, allowing Point objects to be used directly in spatial calculations.
- Return type:
Optional[Coordinate]- Returns:
The Coordinate object, or None if no coordinates are set
- distance_to(other, unit=None)[source]
Calculate distance to another spatial object.
- Parameters:
- Return type:
- Returns:
Distance in specified units, or None if this point or target has no coordinates
Examples
>>> point1 = Point(coordinates=(0, 0)) >>> point2 = Point(coordinates=(1, 1)) >>> distance = point1.distance_to(point2)
- bearing_to(other)[source]
Calculate bearing to another spatial object.
- Parameters:
other (
Union[Coordinate,Point,Placemark,Tuple[float,float],list]) – Target object with coordinates- Return type:
- Returns:
Initial bearing in degrees (0-360), or None if this point or target has no coordinates
Examples
>>> point1 = Point(coordinates=(0, 0)) >>> point2 = Point(coordinates=(1, 0)) # Due east >>> bearing = point1.bearing_to(point2) # Should be ~90°
- objects: KMLManager = <kmlorm.core.managers.KMLManager object>
- midpoint_to(other)[source]
Find geographic midpoint to another spatial object.
- Parameters:
other (
Union[Coordinate,Point,Placemark,Tuple[float,float],list]) – Target object with coordinates- Return type:
Optional[Coordinate]- Returns:
Coordinate at the midpoint, or None if this point or target has no coordinates
Examples
>>> point1 = Point(coordinates=(0, 0)) >>> point2 = Point(coordinates=(2, 2)) >>> midpoint = point1.midpoint_to(point2)
MultiGeometry
Container for multiple geometry types within a single element.
MultiGeometry model for KML multi-geometry collections.
This module defines the MultiGeometry class for handling KML elements that contain multiple geometry types within a single container.
- class kmlorm.models.multigeometry.MultiGeometry(geometries=None, **kwargs)[source]
Bases:
KMLElementRepresents a KML MultiGeometry element.
MultiGeometry elements can contain multiple geometry objects including Points, LineStrings, Polygons, and even nested MultiGeometries. This allows for complex geometric collections within a single KML feature.
- geometries
List of geometry objects (Point, Path, Polygon, MultiGeometry)
- __init__(geometries=None, **kwargs)[source]
Initialize a MultiGeometry with contained geometries.
- add_geometry(geometry)[source]
Add a geometry object to this MultiGeometry.
- get_points()[source]
Get all Point objects from this MultiGeometry.
- get_paths()[source]
Get all Path objects from this MultiGeometry.
- get_polygons()[source]
Get all Polygon objects from this MultiGeometry.
- get_multigeometries()[source]
Get all nested MultiGeometry objects.
- Return type:
List[MultiGeometry]- Returns:
List of nested MultiGeometry objects
- geometry_counts()[source]
Get counts of each geometry type in this MultiGeometry.
- has_coordinates()[source]
Check if any contained geometry has coordinates.
- Return type:
- Returns:
True if any geometry has coordinates
- to_dict()[source]
Convert MultiGeometry to dictionary representation.
- objects: KMLManager = <kmlorm.core.managers.KMLManager object>
Distance and Bearing Methods
Placemark Distance Calculations
The Placemark class provides methods for calculating
distances and bearings between geographic points.
- Placemark.distance_to(other, unit=None)[source]
Calculate distance to another spatial object.
- Parameters:
- Return type:
- Returns:
Distance in specified units, or None if this placemark or target has no coordinates
Examples
>>> placemark1 = Placemark(name="NYC", coordinates=(-74.006, 40.7128)) >>> placemark2 = Placemark(name="London", coordinates=(-0.1276, 51.5074)) >>> distance = placemark1.distance_to(placemark2) >>> print(f"Distance: {distance:.1f} km")
>>> # Different units >>> from kmlorm.spatial import DistanceUnit >>> distance_miles = placemark1.distance_to(placemark2, unit=DistanceUnit.MILES)
>>> # Works with Point and Coordinate objects too >>> from kmlorm.models.point import Point, Coordinate >>> point = Point(coordinates=(0, 0)) >>> coord = Coordinate(longitude=1, latitude=1) >>> distance_to_point = placemark1.distance_to(point) >>> distance_to_coord = placemark1.distance_to(coord)
- Placemark.bearing_to(other)[source]
Calculate bearing to another spatial object.
- Parameters:
other (
Union[Coordinate,Point,Placemark,Tuple[float,float],list]) – Target object with coordinates- Return type:
- Returns:
Initial bearing in degrees (0-360), or None if this placemark or target has no coordinates 0° = North, 90° = East, 180° = South, 270° = West
Examples
>>> placemark1 = Placemark(name="Start", coordinates=(0, 0)) >>> placemark2 = Placemark(name="East", coordinates=(1, 0)) >>> bearing = placemark1.bearing_to(placemark2) # Should be ~90°
Distance Calculation Implementation:
These methods use the same Haversine formula as the QuerySet near() method.
See QuerySets and Managers for detailed information about accuracy, limitations, and appropriate use cases.
Key Features:
Consistent Results: Same algorithm as QuerySet geospatial methods
Flexible Input: Accept either Placemark objects or coordinate tuples
Reliable Accuracy: Within 0.5% for distances up to hundreds of kilometers
Great Circle Distance: True geodesic distance accounting for Earth’s curvature
Distance Calculation Example:
from kmlorm import Placemark
from kmlorm.models.point import Point
# Create two placemarks
baltimore = Placemark(
name="Baltimore, MD",
point=Point(coordinates=(-76.6, 39.3))
)
washington = Placemark(
name="Washington, DC",
point=Point(coordinates=(-77.0, 38.9))
)
# Calculate distance between cities
distance = baltimore.distance_to(washington)
print(f"Distance: {distance:.1f} km") # ≈ 56.3 km
# Calculate using coordinate tuple
distance_to_tuple = baltimore.distance_to((-77.0, 38.9))
print(f"Same distance: {distance_to_tuple:.1f} km")
# Calculate bearing (direction)
bearing = baltimore.bearing_to(washington)
print(f"Bearing: {bearing:.1f}°") # ≈ 225° (southwest)
Return Value Handling:
Both methods return None when coordinates are unavailable:
# Placemark without coordinates
no_coords = Placemark(name="Unknown Location")
result = baltimore.distance_to(no_coords)
if result is None:
print("Cannot calculate distance - missing coordinates")
For complete details about distance calculation accuracy and limitations, see QuerySets and Managers under “Distance Calculation Details”.
Example Usage
from kmlorm import Placemark, Folder, Point
# Create a placemark with coordinates
store = Placemark(
name="Capital Electric",
address="123 Main St, Baltimore, MD",
coordinates=(-76.5, 39.3)
)
# Create a folder to organize placemarks
stores_folder = Folder(name="Electric Stores")
stores_folder.placemarks.add(store)
# Access coordinates
print(f"Store location: {store.longitude}, {store.latitude}")
# Calculate distance to another location
distance = store.distance_to((-76.6, 39.3)) # Distance to Baltimore center
if distance:
print(f"Distance to Baltimore: {distance:.2f} km")
# Validate the placemark
if store.validate():
print("Placemark is valid!")