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: ABCMeta

Metaclass 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: ABC

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

Parameters:
  • element_id (Optional[str]) – Unique identifier for the element

  • name (Optional[str]) – Display name for the element

  • description (Optional[str]) – Descriptive text for the element

  • visibility (bool) – Whether the element is visible in Google Earth

  • **kwargs (Any) – Additional element-specific attributes

__str__()[source]

String representation of the KML element.

Returns the name if available, otherwise the class name and id.

Return type:

str

__repr__()[source]

Developer-friendly representation of the KML element.

Return type:

str

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.

Return type:

Dict[str, Any]

Returns:

Dictionary with all element attributes

update(**kwargs)[source]

Update multiple attributes at once.

Parameters:

**kwargs (Any) – Attribute names and values to update

Return type:

None

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:

bool

Returns:

True if validation passes

Raises:

KMLValidationError – If validation fails

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: KMLElement

Represents 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 description

  • phone_number (Optional[str]) – Contact phone number

  • snippet (Optional[str]) – Short description snippet

  • style_url (Optional[str]) – Reference to KML style definition

  • extended_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]
address: Optional[str]
phone_number: Optional[str]
snippet: Optional[str]
style_url: Optional[str]
extended_data: Optional[Dict[str, Any]]
__str__()[source]

String representation of the Placemark.

Returns name if available, otherwise address, otherwise coordinates.

Return type:

str

property coordinates: Coordinate | None

Get coordinates from the point.

property longitude: float | None

Get the longitude coordinate.

property latitude: float | None

Get the latitude coordinate.

property altitude: float | None

Get the altitude coordinate.

property has_coordinates: bool

Check if placemark has valid coordinates.

to_dict()[source]

Convert placemark to dictionary representation.

Return type:

Dict[str, Any]

Returns:

Dictionary with all placemark attributes

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:
  • other (Union[Coordinate, Point, Placemark, Tuple[float, float], list]) – Target object with coordinates (Coordinate, Point, Placemark, or tuple/list)

  • unit (Optional[DistanceUnit]) – Distance unit (defaults to kilometers)

Return type:

Optional[float]

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:

Optional[float]

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:

bool

Returns:

True if validation passes

Raises:

KMLValidationError – If validation fails

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: KMLElement

Represents 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
__str__()[source]

String representation of the folder.

Return type:

str

to_dict()[source]

Convert folder to dictionary representation.

Return type:

Dict[str, Any]

Returns:

Dictionary with folder attributes and element counts

all_elements()[source]

Get all elements contained in this folder.

Return type:

List[KMLElement]

Returns:

Combined list of all contained elements

total_element_count()[source]

Get total count of all contained elements.

Return type:

int

Returns:

Total number of elements in this folder

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: KMLElement

Represents 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 strings

  • tessellate (bool) – Whether to tessellate the path to follow terrain

  • altitude_mode (str) – How altitude is interpreted (“clampToGround”, “relativeToGround”, “absolute”)

  • **kwargs (Any) – Base element attributes (id, name, description, etc.)

__str__()[source]

String representation of the path.

Return type:

str

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.

Return type:

Dict[str, Any]

Returns:

Dictionary with path attributes

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: KMLElement

Represents 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 boundary

  • inner_boundaries (Optional[List[List[Union[Tuple[float, ...], str]]]]) – List of inner boundary coordinate lists (holes)

  • extrude (bool) – Whether to extrude the polygon to ground level

  • altitude_mode (str) – How altitude is interpreted

  • **kwargs (Any) – Base element attributes (id, name, description, etc.)

__str__()[source]

String representation of the polygon.

Return type:

str

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.

Return type:

Dict[str, Any]

Returns:

Dictionary with polygon attributes

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: object

Represents a geographic coordinate with longitude, latitude, and optional altitude.

longitude

The longitude of the coordinate.

Type:

float

latitude

The latitude of the coordinate.

Type:

float

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:

None

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:

bool

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.

Return type:

dict[str, float]

Returns:

Dictionary with longitude, latitude, and altitude values.

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:
  • other (Union[Coordinate, Point, Placemark, Tuple[float, float], list]) – Target object with coordinates (Coordinate, Point, Placemark, or tuple)

  • unit (Optional[DistanceUnit]) – Distance unit (defaults to kilometers)

Return type:

Optional[float]

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:

Optional[float]

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:

int

Returns:

Hash based on longitude, latitude, and altitude

__init__(longitude, latitude, altitude=0)
class kmlorm.models.point.Point(**kwargs)[source]

Bases: KMLElement

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

property longitude: float | None

Get longitude from coordinates.

property latitude: float | None

Get latitude from coordinates.

property altitude: float | None

Get altitude from coordinates.

has_coordinates()[source]

Check if point has valid coordinates.

Return type:

bool

__str__()[source]

String representation of the Point.

Return type:

str

__repr__()[source]

Detailed representation of the Point.

Return type:

str

validate()[source]

Validate the point’s coordinates.

Return type:

bool

Returns:

True if validation passes

Raises:

Exception – If coordinates are invalid

to_dict()[source]

Convert point to dictionary representation.

Return type:

dict[str, Any]

Returns:

Dictionary containing point properties and coordinate data.

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:
  • other (Union[Coordinate, Point, Placemark, Tuple[float, float], list]) – Target object with coordinates

  • unit (Optional[DistanceUnit]) – Distance unit (defaults to kilometers)

Return type:

Optional[float]

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:

Optional[float]

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: KMLElement

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

Parameters:
  • geometries (Optional[List[Any]]) – List of geometry objects

  • **kwargs (Any) – Additional base element attributes (id, name, etc.)

add_geometry(geometry)[source]

Add a geometry object to this MultiGeometry.

Parameters:

geometry (Any) – A Point, Path, Polygon, or MultiGeometry object

Return type:

None

get_points()[source]

Get all Point objects from this MultiGeometry.

Return type:

List[Any]

Returns:

List of Point objects, including nested ones

get_paths()[source]

Get all Path objects from this MultiGeometry.

Return type:

List[Any]

Returns:

List of Path objects, including nested ones

get_polygons()[source]

Get all Polygon objects from this MultiGeometry.

Return type:

List[Any]

Returns:

List of Polygon objects, including nested ones

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.

Return type:

Dict[str, int]

Returns:

Dictionary with geometry type counts

has_coordinates()[source]

Check if any contained geometry has coordinates.

Return type:

bool

Returns:

True if any geometry has coordinates

to_dict()[source]

Convert MultiGeometry to dictionary representation.

Return type:

Dict[str, Any]

Returns:

Dictionary with all MultiGeometry attributes

__str__()[source]

String representation of the MultiGeometry.

Return type:

str

__repr__()[source]

Detailed representation of the MultiGeometry.

Return type:

str

__len__()[source]

Return the number of contained geometries.

Return type:

int

__iter__()[source]

Iterate over contained geometries.

Return type:

Iterator[Any]

__getitem__(index)[source]

Get geometry by index.

Return type:

Any

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:
  • other (Union[Coordinate, Point, Placemark, Tuple[float, float], list]) – Target object with coordinates (Coordinate, Point, Placemark, or tuple/list)

  • unit (Optional[DistanceUnit]) – Distance unit (defaults to kilometers)

Return type:

Optional[float]

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:

Optional[float]

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!")