Detour Re-ranking

Quick reference

This notebook implements detour reranking from scratch on top of RoutingAPI only, so that the logic can be copied into an application that keeps its own ranking layer. It covers

  • the via-route call

  • the parallel fetch

  • the excursion computation

  • the dur_to sort key

  • the maximum-excursion filter

  • the result annotation

Most-used elements:

  1. RoutingAPI.routes(session, origin, destination, via=Waypoint(lat, lon, street))

  2. RoutingAPI.sections(response) → the at → result and result → stop legs

  3. asyncio.gather(...) over one call per positioned result

  4. excursion = length_to + length_from - baseline_length

  5. sort key dur_to, filter on excursion_m

  6. DetourRanker(credentials, at_pos, stop_pos, routing_api=...), the packaged equivalent

For the high-level equivalent, see the page about DetourRanker. For the complete reference, see the API reference.

Methods used in this notebook

class here_search_demo.routing_api.RoutingAPI(credentials=None, cache=None, raise_for_status=True, options=None, log_fn=None, on_request_sent=None)

https://www.here.com/docs/bundle/routing-api-v8-api-reference/page/index.html

async routes(session, origin, destination, via=None, transport_mode=None, return_fields=None, spans=None, x_headers=None, **kwargs)

Calls the HERE Routing /v8/routes endpoint.

Parameters:
  • session (ClientSession) – instance of HTTPSession

  • origin – route origin, a Waypoint or a (lat, lon[, name_hint]) tuple

  • destination – route destination, in the same formats as origin

  • via – optional intermediate waypoint(s), in the same formats as origin

  • transport_mode (str | None) – overrides the instance transportMode option

  • return_fields (Sequence[str] | None) – overrides the instance return option

  • spans (Sequence[str] | None) – overrides the instance spans option

  • x_headers (dict | None) – Optional X-* headers (X-Request-Id, …)

  • kwargs – additional request URL parameters

Return type:

Response

Returns:

a Response object whose data is the routing payload

static sections(response, route_index=0)

Return the sections of one route of a routing response.

The Routing API starts a new section at each via waypoint and wherever the journey changes transport mode – a Berlin/London route is split by the channel ferry, for instance. Callers that need the at → result and result → stop legs must therefore group these sections with split_at() and merge_sections() rather than assume one section per leg.

Parameters:
  • response (Response) – a Response returned by routes()

  • route_index (int) – index in the routes[] array

Return type:

list[RouteSection]

Returns:

list of RouteSection

class here_search_demo.routing_api.Waypoint(latitude, longitude, name_hint=None)

A Routing API waypoint.

Variables:
  • latitude – waypoint latitude

  • longitude – waypoint longitude

  • name_hint – optional street name passed as the nameHint waypoint option; it helps the router pick the right side of a complex intersection

classmethod make(value)

Return value as a Waypoint.

Parameters:

value – a Waypoint, a (lat, lon) or a (lat, lon, name_hint) tuple

Return type:

Waypoint

Returns:

a Waypoint instance

class here_search_demo.detour.DetourRanker(credentials, at_pos, stop_pos, on_routing_request=None, route_cache=None, routing_api=None)

Reranks search result items by minimal excursion distance from a route.

Parameters

credentials:

HERE API credentials used to authenticate Routing requests.

at_pos:

(latitude, longitude) of the current position on the route. Used as the origin for routing calculations.

stop_pos:

(latitude, longitude) of the route destination.

on_routing_request:

Optional callback invoked before each Routing request that is not served by route_cache.

route_cache:

Route cache shared with RouteEngine, so an already fetched at → stop route is reused as the baseline.

routing_api:

Optional RoutingAPI instance; one is created from credentials when omitted.

async get_route_with_via(session, start_lat, start_lon, via_lat, via_lon, stop_lat, stop_lon, headers, name_hint=None)

Call the Routing API with a via waypoint and return route segments.

Return type:

tuple[int, int, str, int, int, str]

Returns:

(dur_to, dist_to, poly_to, dur_from, dist_from, poly_from) where: - dur_to, dist_to, poly_to: segment from start to via - dur_from, dist_from, poly_from: segment from via to stop

async rerank(resp, all_along=False, max_excursion=None)

Return a new Response whose items are sorted by ascending travel time.

  • When all_along is True items are ranked by dur_to + dur_from (minimise total round-trip time).

  • When all_along is False items are ranked by dur_to only (minimise time to reach the result from the current position; the return leg is shown in the label but does not affect order).

Items whose excursion distance exceeds max_excursion metres are filtered out. Each surviving item gains a _detour annotation, whose most useful keys are:

  • _detour["label"] – <title> (<dur_to>min, <dur_from>min, +<detour_km>km)

  • _detour["rank_before"] – 0-based position of the item in resp, before reranking

  • _detour["polyline_to"] – encoded polyline for the at → item leg

  • _detour["polyline_from"] – encoded polyline for the item → stop leg

The excursion distance is computed relative to the direct at → stop route (not the full route from its origin), so it correctly reflects the extra distance added to the remaining journey.

Parameters

resp:

The original search response.

max_excursion:

Maximum allowed excursion in metres. Items beyond this threshold are dropped from the reranked response.

rtype:

Response

class here_search_demo.api.API(credentials=None, cache=None, raise_for_status=True, options=None, log_fn=None, on_request_sent=None, testing_header=False)

https://docs.here.com/geocoding-and-search/reference

async browse(session, latitude, longitude, categories=None, food_types=None, chains=None, polyline=None, width=None, all_along=None, x_headers=None, **kwargs)

Calls HERE Search Browse endpoint

Parameters:
  • session (ClientSession) – instance of HTTPSession

  • latitude (float) – search center latitude

  • longitude (float) – search center longitude

  • categories (Sequence[str] | None) – Places category ids for filtering

  • food_types (Sequence[str] | None) – Places cuisine ids for filtering

  • chains (Sequence[str] | None) – Places chain ids for filtering

  • x_headers (dict | None) – Optional X-* headers (X-Request-Id, X-AS-Session-ID, …)

Param:

kwargs: additional request URL parameters

Return type:

Response

Returns:

a Response object