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_tosort keythe maximum-excursion filter
the result annotation
Most-used elements:
RoutingAPI.routes(session, origin, destination, via=Waypoint(lat, lon, street))RoutingAPI.sections(response)→ theat → resultandresult → stoplegsasyncio.gather(...)over one call per positioned resultexcursion = length_to + length_from - baseline_lengthsort key
dur_to, filter onexcursion_mDetourRanker(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/routesendpoint.- Parameters:
session (
ClientSession) – instance of HTTPSessionorigin – route origin, a
Waypointor a(lat, lon[, name_hint])tupledestination – 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 instancetransportModeoptionreturn_fields (
Sequence[str] |None) – overrides the instancereturnoptionspans (
Sequence[str] |None) – overrides the instancespansoptionx_headers (
dict|None) – Optional X-* headers (X-Request-Id, …)kwargs – additional request URL parameters
- Return type:
Response- Returns:
a Response object whose
datais 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 → resultandresult → stoplegs must therefore group these sections withsplit_at()andmerge_sections()rather than assume one section per leg.- Parameters:
response (
Response) – aResponsereturned byroutes()route_index (
int) – index in theroutes[]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
nameHintwaypoint option; it helps the router pick the right side of a complex intersection
- 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 fetchedat → stoproute is reused as the baseline.- routing_api:
Optional
RoutingAPIinstance; 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
Responsewhose items are sorted by ascending travel time.When all_along is
Trueitems are ranked bydur_to + dur_from(minimise total round-trip time).When all_along is
Falseitems are ranked bydur_toonly (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_excursionmetres are filtered out. Each surviving item gains a_detourannotation, 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 theat → itemleg_detour["polyline_from"]– encoded polyline for theitem → stopleg
The excursion distance is computed relative to the direct
at → stoproute (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 HTTPSessionlatitude (
float) – search center latitudelongitude (
float) – search center longitudecategories (
Sequence[str] |None) – Places category ids for filteringfood_types (
Sequence[str] |None) – Places cuisine ids for filteringchains (
Sequence[str] |None) – Places chain ids for filteringx_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