geocode/geocode/scotland.py
Edward Betts 90b009fc90 Return nearest parish/polygon for points in the sea near the coast
When a point falls in the sea within a country boundary (e.g. Scotland
Q22 or England Q21) but not within any specific parish, find the nearest
civil parish or high-admin-level polygon within ~0.15 degrees (~10-17km).

- Add get_nearest_scotland_code() for Scottish civil parishes
- Add Polygon.nearest() for general OSM polygon lookup
- Use .limit(1).scalar() in scotland.py for cleaner returns
2026-02-12 18:19:38 +00:00

32 lines
1,008 B
Python

"""Reverse geocode civil parishes in Scotland."""
from sqlalchemy import func
from geocode.database import session
from geocode.model import Scotland
def get_scotland_code(lat: float, lon: float) -> str | None:
"""Find civil parish in Scotland for given lat/lon."""
point = func.ST_Transform(func.ST_SetSRID(func.ST_MakePoint(lon, lat), 4326), 27700)
return (
session.query(Scotland.code)
.filter(func.ST_Contains(Scotland.geom, point))
.limit(1)
.scalar()
)
def get_nearest_scotland_code(
lat: float, lon: float, max_degrees: float = 0.15
) -> str | None:
"""Find nearest civil parish in Scotland within distance."""
point = func.ST_SetSRID(func.ST_MakePoint(lon, lat), 4326)
geom_4326 = func.ST_Transform(Scotland.geom, 4326)
return (
session.query(Scotland.code)
.filter(func.ST_DWithin(geom_4326, point, max_degrees))
.order_by(func.ST_Distance(geom_4326, point))
.limit(1)
.scalar()
)