Route logic (code)

Code-snippet counterpart of the route math appendix. Same sections, same order — the equations are replaced by the implementation they describe. Snippets are pulled from the source at build time, so they cannot drift.

Polyline simplification for route=<polyline>;w=<width>

The tolerance is found by bisection: halve the interval, keep the tolerance whenever the simplified geometry still fits within max_points.

def _do_simplify_polyline(
    bbox_scale: float, iterations: int, line: LineString, max_points: int, points: list[tuple[float, float]]
) -> list[tuple[float, float]]:
    eps_low, eps_high = 0.0, bbox_scale
    best_geo = None

    for _ in range(iterations):
        eps = (eps_low + eps_high) / 2
        simplified = _shapely_simplify(line, eps, preserve_topology=False)
        if get_num_coordinates(simplified) <= max_points:
            best_geo = simplified
            eps_high = eps
        else:
            eps_low = eps

    if best_geo is None:
        return points

    return [tuple(row) for row in get_coordinates(best_geo)]

The entry point short-circuits when the polyline is already small enough, and derives the initial upper bound from the bounding-box scale:

def simplify_polyline(
    points: list[tuple[float, float]],
    max_points: int,
    iterations: int = 15,
) -> list[tuple[float, float]]:
    """Reduce ``points`` to at most ``max_points`` using GEOS Douglas–Peucker."""
    n = len(points)
    if n <= max_points:
        return points
    if max_points < 2:
        raise ValueError("max_points must be >= 2")

    flat = _build_flat_coord_array(points)
    line = LineString(_pairs_from_flat(flat))
    bbox_scale = _bbox_scale_from_flat(flat)

    return _do_simplify_polyline(bbox_scale, iterations, line, max_points, points)

Corridor geometry from route width

A local tangent-plane projection centred on the route centroid gives metre units, so buffer(width) means metres on the ground:

def _local_metric_projectors(ref_lat: float, ref_lon: float):
    """Return forward/inverse local tangent-plane projectors.

    The forward projector maps ``(lon, lat)`` to local metres around a fixed
    reference point. The inverse projector maps local metres back to WGS84-like
    lon/lat coordinates.
    """
    cos_lat0 = math.cos(math.radians(ref_lat))
    cos_lat0 = max(cos_lat0, 1e-12)  # protect inverse projection near poles

    def to_local(lon: float, lat: float) -> tuple[float, float]:
        x = _EARTH_RADIUS_M * math.radians(lon - ref_lon) * cos_lat0
        y = _EARTH_RADIUS_M * math.radians(lat - ref_lat)
        return x, y

    def to_wgs84(x: float, y: float) -> tuple[float, float]:
        lon = ref_lon + math.degrees(x / (_EARTH_RADIUS_M * cos_lat0))
        lat = ref_lat + math.degrees(y / _EARTH_RADIUS_M)
        return lon, lat

    return to_local, to_wgs84
async def build_corridor(
    points: list[_Point],
    width: int,
):
    """Return a Shapely polygon that is a ``width``-metre buffer around the polyline.

    Parameters
    ----------
    points:
        Route points in ``(lat, lon)`` or ``(lat, lon, z)`` order.
    width:
        Buffer width in metres.
    """
    if not points:
        raise ValueError("points must not be empty")

    line = LineString((float(p[1]), float(p[0])) for p in points)

    ref_lat = float(line.centroid.y)
    ref_lon = float(line.centroid.x)
    to_local, to_wgs84 = _local_metric_projectors(ref_lat, ref_lon)
    line_local = LineString([to_local(lon, lat) for lon, lat in line.coords])
    buffer_local = line_local.buffer(width)
    return transform(to_wgs84, buffer_local)

min from pos future position

Elapsed trip time at the anchor — full durations of earlier spans plus a waypoint-index-proportional fraction of the anchor’s own span:

def elapsed_sec_at_position(spans: list, waypoints: list, lat: float, lon: float) -> float:
    """Return the elapsed seconds from the route start to the waypoint closest to ``(lat, lon)``.

    Each span dict must contain ``offset`` (int) and ``duration`` (float, seconds).
    Following the HERE Routing API convention, ``spans[i]['offset']`` is the index of the
    **first** waypoint of span *i*, so span *i* covers the waypoints up to
    ``spans[i + 1]['offset']`` (the last waypoint for the last span).
    """
    # Find the closest waypoint by squared Euclidean distance (fast proxy).
    min_dist2 = float("inf")
    closest_idx = 0
    for i, wp in enumerate(waypoints):
        d2 = (lat - wp[0]) ** 2 + (lon - wp[1]) ** 2
        if d2 < min_dist2:
            min_dist2 = d2
            closest_idx = i

    elapsed = 0.0
    last_index = len(waypoints) - 1
    for i, span in enumerate(spans):
        span_start = span["offset"]
        span_end = spans[i + 1]["offset"] if i + 1 < len(spans) else last_index
        if closest_idx <= span_end:
            span_width = span_end - span_start
            if span_width > 0:
                elapsed += span["duration"] * (closest_idx - span_start) / span_width
            return elapsed
        elapsed += span["duration"]
    return elapsed

Mapping the target elapsed time back to a position, walking span waypoints by accumulated great-circle length:

def position_at_x_sec_ahead(spans: list, waypoints: list, elapsed: float, x_sec: float) -> tuple[float, float]:
    """Return the ``(lat, lon)`` that is ``x_sec`` seconds ahead of ``elapsed`` along the route.

    If the target is beyond the end of the route the final waypoint is returned.
    """
    if not waypoints:
        raise ValueError("waypoints must not be empty")

    target = elapsed + x_sec
    acc = 0.0
    last_index = len(waypoints) - 1
    for i, span in enumerate(spans):
        span_dur = span.get("duration", 0)
        span_len_m = span.get("length", 0)
        if acc + span_dur > target:
            fraction = (target - acc) / span_dur if span_dur > 0 else 0.0
            target_dist = span_len_m * fraction
            span_start = span["offset"]
            span_end = spans[i + 1]["offset"] if i + 1 < len(spans) else last_index
            pts = waypoints[span_start : span_end + 1]
            if len(pts) < 2:
                return pts[0] if pts else waypoints[-1]
            cum = 0.0
            for j in range(len(pts) - 1):
                lat1, lon1 = pts[j]
                lat2, lon2 = pts[j + 1]
                seg = haversine_m(lat1, lon1, lat2, lon2)
                if cum + seg >= target_dist:
                    seg_frac = (target_dist - cum) / seg if seg > 1e-9 else 0.0
                    return lat1 + (lat2 - lat1) * seg_frac, lon1 + (lon2 - lon1) * seg_frac
                cum += seg
            return pts[-1]
        acc += span_dur
    return waypoints[-1]
def haversine_m(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
    """Great-circle distance in metres between two ``(lat, lon)`` points."""
    dlat = math.radians(lat2 - lat1)
    dlon = math.radians(lon2 - lon1)
    a = math.sin(dlat / 2) ** 2 + math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) * math.sin(dlon / 2) ** 2
    return _EARTH_RADIUS_M * 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))

Detour reranking

Excursion distance and ranking key:

    def excursion_m(self, direct_dist_m: int) -> int:
        """Extra distance vs. the direct ``at → stop`` route, in metres."""
        return self.dist_to + self.dist_from - direct_dist_m
    def sort_key(self, all_along: bool) -> float:
        """Ranking key in minutes: round-trip time when *all_along*, else time to reach."""
        seconds = self.dur_to + self.dur_from if all_along else self.dur_to
        return seconds / 60

Filtering, scoring and sorting happen in one pass over the results:

    @staticmethod
    def _annotate_item(item: dict, legs: _DetourLegs, excursion_m: int, rank_before: int) -> dict:
        """Return a copy of *item* with a ``_detour`` annotation attached."""
        dur_to_min = int(legs.dur_to / 60)
        dur_from_min = int(legs.dur_from / 60)
        excursion_km = abs(int(excursion_m / 1000))
        excursion_sign = "+" if excursion_m >= 0 else "-"
        annotated = dict(item)
        annotated["_detour"] = {
            "label": f"{item.get('title', '')} ({dur_to_min}min, {dur_from_min}min, {excursion_sign}{excursion_km}km)",
            "rank_before": rank_before,
            "dur_to_sec": legs.dur_to,
            "dur_from_sec": legs.dur_from,
            "dist_to_m": legs.dist_to,
            "dist_from_m": legs.dist_from,
            "excursion_m": excursion_m,
            "polyline_to": legs.poly_to,
            "polyline_from": legs.poly_from,
        }
        return annotated