Distance, Area, and Nearest Neighbors
Distance and area are properties of a geometry model and coordinate system, not just pairs of numbers. Planar Shapely and GeoPandas calculations return values in coordinate units. Longitude-latitude degrees therefore cannot be reported as metres or square metres.
Prerequisites
Complete spatial joins, overlay, and dissolve. You should be able to state which geometry represents each object and whether a boundary match is permitted.
Learning goals
- Choose between local projected and ellipsoidal distance calculations.
- Compute planar distance and area in explicit metre-based units.
- Use nearest joins with a maximum distance and multi-match policy.
- Explain centroid, boundary, antimeridian, elevation, and network-distance limitations.
Define what is being measured
Point-to-point straight-line distance may be useful for a small local screen. It is not walking distance, travel time, line-of-sight, or distance between full facility footprints. Polygon distance is zero when polygons touch or overlap; centroid distance can be positive and can place a centroid outside a concave polygon. Name the geometry support and metric.
For the Berlin fixture, projecting all features to WGS 84 / UTM zone 33N makes GeoPandas' planar results metres and square metres. An ellipsoidal calculation with pyproj.Geod provides a useful point-to-point comparison without first projecting. Agreement after rounding on this short local segment is a check, not evidence that UTM 33N is safe globally.
sjoin_nearest can return multiple rows for equidistant nearest neighbors. Use max_distance to enforce the domain's search radius and improve query performance, retain unmatched rows when they are meaningful, and define how ties are reported. Never break ties by incidental row order.
Worked example
import json
from pathlib import Path
import geopandas as gpd
from pyproj import Geod
fixture = Path("tests/fixtures/geospatial-data-science")
def load(name):
document = json.loads((fixture / name).read_text(encoding="utf-8"))
return gpd.GeoDataFrame.from_features(document["features"], crs=document["metadata"]["crs"])
places = load("places.geojson")
districts = load("districts.geojson")
projected_places = places.to_crs("EPSG:32633").set_index("place_id")
projected_districts = districts.to_crs("EPSG:32633")
planar = projected_places.geometry["west-library"].distance(projected_places.geometry["boundary-stop"])
geodesic = Geod(ellps="WGS84").inv(13.39, 52.52, 13.4, 52.52)[2]
areas = projected_districts.assign(area_km2=projected_districts.area / 1_000_000)
north = projected_places.loc[["north-kiosk"]].reset_index()
nearest = north.sjoin_nearest(
projected_districts[["district_id", "geometry"]],
how="left",
max_distance=2_000,
distance_col="distance_m",
)
area_text = ", ".join(
f"{row.district_id}={row.area_km2:.3f}" for row in areas.sort_values("district_id").itertuples()
)
print(f"west_to_boundary_projected_m={planar:.0f} geodesic_m={geodesic:.0f}")
print(f"district_area_km2={area_text}")
print(f"north_nearest={nearest['district_id'].iloc[0]} distance_m={nearest['distance_m'].iloc[0]:.0f}")
Expected output:
west_to_boundary_projected_m=679 geodesic_m=679
district_area_km2=east=3.020, west=3.020
north_nearest=east distance_m=556
The nearest distance is from the point to the polygon boundary, not to a district centroid. The 2 km maximum is part of the query contract; a more distant point would remain unmatched in a left join.
Global and operational boundaries
Ellipsoidal distance solves a geodesic problem on a reference ellipsoid. A route crossing the antimeridian needs longitude wrapping and geometry segmentation handled explicitly; naive planar coordinates can imply a path across almost the whole map. For polygons spanning large areas, choose an appropriate equal-area approach or ellipsoidal area method and define ring orientation.
Elevation is absent here, so calculations are two-dimensional. Network travel needs a routable graph, direction, impedance, restrictions, and time assumptions. Measurement uncertainty can dominate sub-metre numerical precision; round and report results accordingly.
Limitations and common mistakes
- Never interpret
.distanceor.areaon a geographic CRS as metres or square metres. - Web Mercator is convenient for display but is not a general measurement CRS.
- Nearest does not mean reachable, eligible, available, or causally influential.
- Ties, maximum distance, empty geometry, and missing geometry require explicit outcomes.
- Index acceleration does not remove the need to validate CRS and metric assumptions.
Practice
Design a “nearest clinic” contract with origin geometry, clinic eligibility time, metric, maximum distance, tie behavior, unmatched behavior, CRS, and uncertainty. Then state what extra data is required to change the answer to “fastest reachable clinic.”
Next steps
This completes the spatial-foundations batch. Continue directly with cartographic encoding and accessible maps, which begins Ticket 56 with map communication before raster processing and movement workflows.
Primary sources
Checked 2026-10-18: Shapely, planar coordinate-system and measurement guidance; GeoPandas, sjoin_nearest and projection guidance; pyproj, Geod API; PROJ, geodesic distance functions.