API Reference¶
This page centralizes the public API surface used by the demo and notebooks.
Core modules¶
here_search_demo.api¶
- 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)¶
Bases:
SearchEndpointsMixinhttps://docs.here.com/geocoding-and-search/reference
- BASE_URL = {Endpoint.AUTOSUGGEST: 'https://autosuggest.search.hereapi.com/v1/autosuggest', Endpoint.AUTOSUGGEST_HREF: 'https://discover.search.hereapi.com/v1/discover', Endpoint.DISCOVER: 'https://discover.search.hereapi.com/v1/discover', Endpoint.LOOKUP: 'https://lookup.search.hereapi.com/v1/lookup', Endpoint.BROWSE: 'https://browse.search.hereapi.com/v1/browse', Endpoint.REVGEOCODE: 'https://revgeocode.search.hereapi.com/v1/revgeocode', Endpoint.SIGNALS: 'https://signals.search.hereapi.com/v1/signals'}¶
- cache: dict[str, Response]¶
- property credentials: Credentials¶
Return the credentials object.
- async lookup(session, id, x_headers=None, **kwargs)¶
Calls HERE Search Lookup for a specific id
- Parameters:
session (
ClientSession) – instance of HTTPSessionid (
str) – location record IDx_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
- async reverse_geocode(session, latitude, longitude, x_headers=None, **kwargs)¶
Calls HERE Reverse Geocode for a geo position
- Parameters:
session (
ClientSession) – instance of HTTPSessionlatitude (
float) – input position latitudelongitude (
float) – input position longitudex_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
- async signals(session, resource_id, correlation_id, rank, action, x_headers=None, **kwargs)¶
Calls HERE Search Signals endpoint to report a user action on a result.
- Parameters:
session (
ClientSession) – instance of HTTPSessionresource_id (
str) – the HERE result id on which the action is performedcorrelation_id (
str) – the X-Correlation-ID from the response that produced this resultrank (
int) – the rank of the result in its result listaction (
str) – the action performed by the user (e.g. “here:gs:action:view”, “start”, “end”)x_headers (
dict|None) – Optional X-* headers (X-User-ID, …)kwargs – additional body parameters (e.g. userId, asSessionId)
- Return type:
Response|None- Returns:
a Response object, or None on failure
here_search_demo.widgets.app¶
- class here_search_demo.widgets.app.OneBoxMap(credentials=None, user_profile=None, results_limit=None, suggestions_limit=None, terms_limit=None, place_taxonomy_buttons=None, extra_api_params=None, on_map=False, fuel=False, tripadvisor=False, recommendations=False, map_only=False, options=None, testing_header=False, **kwargs)¶
Bases:
OneBoxControlsMixin,OneBoxResultsMixin,UserProfileMixin,OneBoxCoreInteractive one-box search application with map and result panels.
OneBoxMapwires text input, taxonomy shortcuts, map rendering and result/details handling into a ready-to-use demo widget.- Parameters:
credentials (
Credentials|None) – Optional credentials provider.user_profile (
UserProfile|None) – Optional user profile controlling language/signals.results_limit (
int|None) – Max displayed results.suggestions_limit (
int|None) – Max displayed suggestions.terms_limit (
int|None) – Max displayed term buttons.place_taxonomy_buttons (
PlaceTaxonomyButtons|None) – Optional custom taxonomy buttons widget.extra_api_params (
dict|None) – Extra params forwarded to API requests.on_map (
bool) – Whether to display controls on map.fuel (
bool) – Enable fuel details.tripadvisor (
bool) – Enable TripAdvisor details.recommendations (
bool) – Enable recommendation reranking flow.map_only (
bool) – Hide JSON/log panels and keep map-centric layout.options (
APIOptions|None) – Optional prebuilt API options.testing_header (
bool) – Include NLP testing header for API calls.kwargs – Forwarded widget/layout options.
- buttons_box_w: PlaceTaxonomyButtons¶
- clear_logs()¶
- clear_query_text()¶
- cors_allow_user_id_header: bool = False¶
- credentials: Credentials¶
- credentials_properties: CredentialsLoader¶
- default_icons = ('fa-gas-pump', 'fa-charging-station', 'fa-utensils', 'fa-bed', 'fa-parking', 'fa-euro-sign', 'fa-pizza-slice', 'fa-hamburger')¶
- default_options = APIOptions(endpoint={<Endpoint.AUTOSUGGEST: 1>: {'show': 'details'}, <Endpoint.AUTOSUGGEST_HREF: 2>: {'show': 'ev'}, <Endpoint.DISCOVER: 3>: {'show': 'ev'}, <Endpoint.BROWSE: 5>: {'show': 'ev'}, <Endpoint.LOOKUP: 4>: {'show': 'ev'}}, lookup_has_more_details=True)¶
- default_output_format = 'text'¶
- default_placeholder = 'free text'¶
- default_search_box_layout = {'width': '240px'}¶
- default_taxonomy = example(gas(['700-7600-0000', '700-7600-0116', '700-7600-0444'], None, None), ev(['700-7600-0322', '700-7600-0323', '700-7600-0324'], None, None), eat(['100'], None, None), sleep(['500-5000'], None, None), park(['400-4300', '800-8500'], None, None), ATM(['700-7010-0108'], None, None), pizza(None, ['800-057'], None), fastfood(None, None, ['1566', '1498']))¶
- log_handler: TableLogWidget | None¶
- logger: Logger¶
- map_only: bool¶
- map_w: ResponseMap¶
- query_box_w: SubmittableTextBox¶
- query_terms_w: TermsButtons¶
- result_buttons_w: SearchResultButtons¶
- result_json_w: SearchResultJson | None¶
- result_queue: Queue¶
- routing_api_calls: int¶
- search_api_calls: int¶
- search_center_label_w: Label¶
- async search_events_preprocess(session)¶
Send a ‘start’ signal when the app begins processing events.
- Return type:
None
- show()¶
Display the application UI in the current notebook.
This displays the internal root widget without exposing or returning the underlying display handle.
- Return type:
None
- state: SearchState¶
- async stop()¶
Send an ‘end’ signal then stop the event loop.
- triage_intent(intent, context)¶
Resolve an intent into a SearchEvent, handler and config.
Keeps routing declarative via TRIAGES for most kinds; only the inherently irregular “details” case is handled specially.
here_search_demo.widgets.credentials¶
- class here_search_demo.widgets.credentials.CredentialsLoader(*args: t.Any, **kwargs: t.Any)¶
Bases:
AnyWidget- CREDENTIAL_KEYS = ('here.token.endpoint.url', 'here.access.key.id', 'here.access.key.secret', 'here.api.key')¶
- active_config¶
An instance of a Python dict.
One or more traits can be passed to the constructor to validate the keys and/or values of the dict. If you need more detailed validation, you may use a custom validator method.
Changed in version 5.0: Added key_trait for validating dict keys.
Changed in version 5.0: Deprecated ambiguous
trait,traitsargs in favor ofvalue_trait,per_key_traits.
here_search_demo.api_options¶
- class here_search_demo.api_options.APIOption(key, values)¶
Bases:
objectBase representation of a query option contributed to one or more endpoints.
- Variables:
key (str) – Query parameter name (for example
"show"or"at").values (Sequence[str]) – One or more values attached to
key.endpoints (list) – Endpoints where this option is valid.
for_more_details (bool) – Whether option implies lookup-based enrichment.
incompatible_with (list) – Option classes that cannot coexist with this option.
- endpoints = []¶
- for_more_details = False¶
- incompatible_with = []¶
- key: str¶
- values: Sequence[str]¶
- class here_search_demo.api_options.APIOptions(options)¶
Bases:
objectNormalized endpoint-to-query-options map used by
here_search_demo.api.API.endpointstores merged query parameters per endpoint where repeated values are deduplicated and joined with commas.- Variables:
endpoint (dict) – Mapping
Endpoint -> {query_key: csv_values}.lookup_has_more_details (bool) – Whether any option requires lookup enrichment.
- endpoint: dict[str, dict[str, str]]¶
- lookup_has_more_details: bool¶
- class here_search_demo.api_options.At(latitude, longitude)¶
Bases:
APIOptionLocation center option (at=<lat>,<lon>) for search endpoints.
- endpoints = (Endpoint.DISCOVER, Endpoint.AUTOSUGGEST, Endpoint.BROWSE, Endpoint.REVGEOCODE)¶
- class here_search_demo.api_options.Details¶
Bases:
APIOptionRequest autosuggest details payload (show=details).
- endpoints = (Endpoint.AUTOSUGGEST,)¶
- class here_search_demo.api_options.EVDetails¶
Bases:
APIOptionRequest electric-vehicle details (show=ev).
- endpoints = (Endpoint.AUTOSUGGEST_HREF, Endpoint.DISCOVER, Endpoint.LOOKUP, Endpoint.BROWSE)¶
- for_more_details = True¶
- class here_search_demo.api_options.FuelDetails¶
Bases:
APIOptionRequest fuel-station metadata (show=fuel).
- endpoints = (Endpoint.AUTOSUGGEST, Endpoint.AUTOSUGGEST_HREF, Endpoint.DISCOVER, Endpoint.LOOKUP, Endpoint.BROWSE)¶
- class here_search_demo.api_options.FuelPriceDetails¶
Bases:
APIOptionRequest fuel and fuel-price data (show=fuel,fuelPrices).
- endpoints = (Endpoint.AUTOSUGGEST_HREF, Endpoint.DISCOVER, Endpoint.LOOKUP, Endpoint.BROWSE)¶
- class here_search_demo.api_options.RecommendPlaces¶
Bases:
APIOptionRequest recommendation enrichment (with=recommendPlaces).
- endpoints = (Endpoint.AUTOSUGGEST, Endpoint.AUTOSUGGEST_HREF, Endpoint.DISCOVER)¶
- for_more_details = True¶
- incompatible_with = [<class 'here_search_demo.api_options.Route'>]¶
- class here_search_demo.api_options.Route(polyline, width)¶
Bases:
APIOptionRoute corridor option (route=<polyline>;w=<width>) for search endpoints.
- endpoints = (Endpoint.DISCOVER, Endpoint.AUTOSUGGEST, Endpoint.BROWSE)¶
- class here_search_demo.api_options.Triggers400¶
Bases:
APIOptionTesting option intentionally producing an invalid
showvalue.- endpoints = (Endpoint.AUTOSUGGEST, Endpoint.DISCOVER, Endpoint.LOOKUP, Endpoint.BROWSE)¶
- class here_search_demo.api_options.TripadvisorDetails¶
Bases:
APIOptionRequest TripAdvisor details in responses.
- endpoints = (Endpoint.AUTOSUGGEST_HREF, Endpoint.DISCOVER, Endpoint.LOOKUP, Endpoint.BROWSE)¶
- for_more_details = True¶
- class here_search_demo.api_options.TruckDetails¶
Bases:
APIOptionRequest truck-related metadata (show=truck).
- endpoints = (Endpoint.AUTOSUGGEST, Endpoint.AUTOSUGGEST_HREF, Endpoint.DISCOVER, Endpoint.LOOKUP, Endpoint.BROWSE)¶
- class here_search_demo.api_options.TruckFuelPriceDetails¶
Bases:
APIOptionRequest truck and fuel-price data (show=truck,fuelPrices).
- endpoints = (Endpoint.AUTOSUGGEST_HREF, Endpoint.DISCOVER, Endpoint.LOOKUP, Endpoint.BROWSE)¶
- here_search_demo.api_options.build_api_options(config, extra_options=())¶
Build
APIOptionsfrom base config and optional extra options.Extra options are appended per endpoint only when applicable, then options declared as incompatible are removed.
- Parameters:
config – Base mapping
Endpoint -> sequence[APIOption].extra_options – Additional options to merge into the base config.
- Returns:
Normalized options container.
- Return type:
here_search_demo.user¶
- class here_search_demo.user.DefaultUser(**kwargs)¶
Bases:
UserProfileConvenience profile with positioning enabled and sharing disabled.
- class here_search_demo.user.UserProfile(use_positioning, share_experience, api=None, start_position=None, api_options=None, preferred_languages=None, name=None)¶
Bases:
objectUser preferences and runtime context for one-box interactions.
The profile stores consent flags, language preferences and the latest known user position. It can resolve locale information from coordinates through reverse geocoding and lookup calls.
- Variables:
name (str) – Human-readable profile name.
id (str) – Stable profile identifier derived from name and host node.
api (API) – API adapter used for locale lookup operations.
preferred_languages (dict) – Mapping of country code (or
None) to language.has_country_preferences (bool) – Whether country-specific preferences exist.
api_options (APIOptions) – Extra API options associated with this profile.
preferred_language (str) – Default language fallback for the profile.
current_latitude (float) – Latest latitude associated with the profile.
current_longitude (float) – Latest longitude associated with the profile.
current_position_country (str) – Latest resolved country code.
- berlin = (52.51604, 13.37691)¶
- current_latitude: float¶
- current_longitude: float¶
- current_position_country: str¶
- default_country_code = 'DEU'¶
- default_current_position = (52.51604, 13.37691)¶
- default_language = 'en'¶
- default_name = 'default'¶
- default_profile_languages = {'default': 'en'}¶
- get_current_language()¶
Return effective language for the current position context.
- get_preferred_country_language(country_code)¶
Return preferred language for a specific country.
Falls back to the default profile entry when no country match exists.
- Parameters:
country_code (
str) – ISO-like country code.- Returns:
Preferred language for the country, or
None.
- async get_preferred_locale(latitude, longitude)¶
Resolve country and language for a coordinate pair.
- Parameters:
latitude (
float) – Latitude to resolve.longitude (
float) – Longitude to resolve.
- Returns:
(country_code, language)from HERE responses.- Return type:
tuple[str | None, str | None]
- preferred_languages: dict¶
- send_signal(body)¶
Send a user signal payload.
- Parameters:
body (
list) – Signal payload.
- async set_position(latitude, longitude)¶
Update current position and refresh locale-derived preferences.
- Parameters:
latitude – Current latitude.
longitude – Current longitude.
- Returns:
Current profile instance.
- Return type:
Whether the user has opted in to experience sharing.
- property use_positioning¶
Whether the user has opted in to position usage.
Classes used in obm_*.ipynb¶
- class here_search_demo.base.OneBoxCore(api=None, queue=None, search_center=None, language=None, results_limit=None, suggestions_limit=None, terms_limit=None, max_transient_keep=None)¶
Bases:
objectCore async controller for one-box search workflows.
OneBoxCoreconsumesSearchIntentobjects fromqueue, maps them to typed search events, executes API calls, and dispatches responses to dedicated handlers.Subclasses typically override presentation hooks such as
handle_suggestion_list(),handle_result_list(), andhandle_result_details()while reusing the routing/transport pipeline.- Parameters:
api (
API|None) – API adapter. Defaults tohere_search_demo.api.API.queue (
Queue|None) – Intent queue consumed byrun().search_center (
Tuple[float,float] |None) – Default(lat, lon)context used by requests.language (
str|None) – Preferred language code for requests.results_limit (
int|None) – Number of results to expose to UI handlers.suggestions_limit (
int|None) – Number of autosuggest items to expose.terms_limit (
int|None) – Number of term suggestions to expose.max_transient_keep (
int|None) – Maximum queued transient-text intents retained.
- add_postprocess(callback)¶
Register an async callback(intent, event, resp, session) to be called after every processed search event.
Multiple callbacks are called in registration order. Use
remove_postprocessto deregister.Example:
results_ready = asyncio.Event() async def wait_for_results(intent, event, resp, session): if intent.kind in ("submitted_text", "taxonomy"): results_ready.set() app.add_postprocess(wait_for_results) app.buttons_box_w.buttons[0].click() await results_ready.wait() app.remove_postprocess(wait_for_results)
- Return type:
None
- handle_action(intent, response)¶
Called after an ActionSearchEvent has sent its signal for a LocationResponseItem click. No lookup was performed;
responsewill beNone.- Return type:
None
- handle_empty_text_submission(intent, response)¶
- Typically
called in OneBoxCore.handle_search_event()
associated with OneBoxCore.EmptySearchEvent via self.intent_routes
- Parameters:
intent (
SearchIntent) – Response intentresponse (
Response) – Response instance
- Return type:
None- Returns:
None
- handle_result_details(intent, response)¶
- Typically
called in OneBoxCore.handle_search_event()
associated with OneBoxCore.DetailsSearchEvent via self.intent_routes
- Parameters:
intent (
SearchIntent) – Response intentresponse (
Response) – Response instance
- Return type:
None- Returns:
None
- handle_result_list(intent, response)¶
- Typically
called in OneBoxCore.handle_search_event()
associated with OneBoxCore.TextSearchEvent and OneBoxCore.PlaceTaxonomySearchEvent via self.intent_routes
- Parameters:
intent (
SearchIntent) – Response intentresponse (
Response) – Response instance
- Return type:
None- Returns:
None
- async handle_search_event(session)¶
Handle a single search event and return (intent, event, response).
This helper is used by tests and subclasses; it processes one intent using the same routing as handle_search_events.
- Return type:
tuple[SearchIntent,SearchEvent,Response]
- async handle_search_events()¶
This method repeatedly waits for search events.
- handle_suggestion_list(intent, response)¶
- Typically
called in OneBoxCore.handle_search_event()
associated with OneBoxCore.PartialTextSearchEvent via self.intent_routes
- Parameters:
intent (
SearchIntent) – Response intentresponse (
Response) – Response instance
- Return type:
None- Returns:
None
- remove_postprocess(callback)¶
Remove a previously registered postprocess callback (no-op if absent).
- Return type:
None
- run(handle_search_events=None)¶
Start the background consumer task and return
self.- Parameters:
handle_search_events (
Callable|None) – Optional coroutine factory replacing the default event loop handler.- Returns:
Running app instance.
- Return type:
- async search_event_postprocess(intent, event, resp, session)¶
Run all registered postprocess callbacks in registration order.
- Return type:
None
- async stop()¶
Wait until queue is empty and background task has finished.
- In Jupyter, await app.stop() will keep the cell busy until:
all queued intents are processed, and
the consumer task has exited.
- triage_intent(intent, context)¶
Resolve an intent into a SearchEvent, handler and config.
Keeps routing declarative via TRIAGES for most kinds; only the inherently irregular “details” case is handled specially.
- Return type:
tuple[SearchEvent,Callable[[SearchIntent,Response],None],EndpointConfig|LookupConfig|NoConfig|None]
- async wait_for_search_event()¶
Wait for the next intent, and resolve it via triage_intent.
- Return type:
tuple[SearchIntent,SearchEvent,Callable[[SearchIntent,Response],None],EndpointConfig|LookupConfig|NoConfig|None]
- class here_search_demo.auth.Credentials¶
Bases:
objectCredential and token provider for HERE API requests.
The class resolves credentials from environment variables and/or local credentials files, then exposes either an API key or OAuth access token. Token values are cached and refreshed before expiration.
Environment variable precedence for API key:
HERE_ACCESS_KEY_ID+HERE_ACCESS_KEY_SECRET>HERE_API_KEY>API_KEY.- Variables:
default_auth_url (str) – Default OAuth token endpoint.
- property active_config: dict[str, str]¶
Return a credentials-loader compatible config when fully available.
- apply_active_config(active_config)¶
Update credentials from a validated credentials-loader config mapping.
- Return type:
None
- property atoken: dict¶
Return an OAuth access token using the async transport.
This path is intended for browser runtimes (Pyodide/JupyterLite). The token is cached in memory and refreshed when close to expiry.
- Returns:
OAuth access token, or
Nonewhen OAuth credentials are unavailable.- Return type:
str | None
- property token: str | None¶
Return an OAuth access token using the synchronous transport.
This path is intended for standard CPython runtimes. The token is cached in memory and refreshed when close to expiry.
- Returns:
OAuth access token, or
Nonewhen OAuth credentials are unavailable.- Return type:
str | None
- class here_search_demo.widgets.input_text.SubmittableTextBox(queue, state, *args, **kwargs)¶
Bases:
HBoxA ipywidgets HBox made of a SubmittableText and a lens Button
- async feed(text, delay=None)¶
Type text programmatically into the input widget.
Useful for notebook demos/tests that simulate user typing.
"\b"characters are interpreted as backspace.- Parameters:
text – Text sequence to inject.
delay (
float|None) – Delay in seconds between characters. Defaults todefault_simulation_delay_sec.
- submit()¶
Programmatically trigger a submit.
- class here_search_demo.widgets.input_text.SubmittableText(*args: t.Any, **kwargs: t.Any)¶
Bases:
TextA ipywidgets Text class enhanced with an on_submit() method
- on_submit(callback, remove=False)¶
(Un)Register a callback to handle text submission.
Triggered when the user clicks enter.
Parameters¶
- callback: callable
Will be called with exactly one argument: the Widget instance
- remove: bool (optional)
Whether to unregister the callback
- trigger_submit()¶
Programmatically invoke all registered submit callbacks.
This mirrors the behavior when the front-end fires a
submitcustom event, without reaching into private attributes from outside this subclass.- Return type:
None
- class here_search_demo.widgets.input_text.TermsButtons(target_text_box, state, values=None, buttons_count=None, index=-1, layout=None)¶
Bases:
HBoxSuggestion buttons bound to a
SubmittableTextBox.The widget renders one button per value in
state.term_suggestions. Clicking a button replaces one token in the target text box and updatesSearchState.- Parameters:
target_text_box (
SubmittableTextBox) – Text widget to update when a button is clicked.state (
SearchState) – Shared search state carrying the current term suggestions.values (
list[str] |None) – Optional initial suggestions; when provided they are stored instate.term_suggestionsbefore rendering.buttons_count (
int|None) – Number of buttons to create when no suggestions are available yet.index (
int) – Token index to replace in the target query.-1replaces the last token,Nonereplaces the whole query text.layout (
dict|None) – Optional ipywidgets layout for the button container.
- class here_search_demo.widgets.input_text.PlaceTaxonomyButtons(queue, taxonomy, icons, state)¶
Bases:
HBoxButtons that emit taxonomy search intents.
Each button maps to one
PlaceTaxonomyItem. On click, the selected taxonomy item is stored instateand aSearchIntent(kind="taxonomy", ...)is pushed toqueue.- Parameters:
queue (
Queue) – Queue receiving taxonomy intents.taxonomy (
PlaceTaxonomy) – Taxonomy source used to create buttons.icons (
Sequence[str]) – Icons/text labels paired with taxonomy items.state (
SearchState) – Shared search state updated with the selected taxonomy item.
- class here_search_demo.widgets.state.SearchState¶
Bases:
objectWidget-local search view state.
This object keeps presentation-oriented data that helps widgets render the current response and preserve UI interactions between updates.
- class here_search_demo.widgets.util.Output(*args: t.Any, **kwargs: t.Any)¶
Bases:
Output
- class here_search_demo.widgets.output_map.ResponseMap(queue=None, state=None, search_center_handler=None, tile_opacity=0.6, **kwargs)¶
Bases:
PositionMap,DetailsMixin,LabelsMixinMap widget used to render search responses and selection actions.
The map displays results as GeoJSON markers, optionally adds extra labels (fuel prices / TripAdvisor), and can fit bounds to returned items. It is also interactive: marker clicks push
ActionIntentinstances toqueueso upper layers can retrieve details or trigger detour logic.- Parameters:
queue (
Queue|None) – Queue used for emitted intents from map interactions.state (
SearchState|None) – Shared state containing ranked response items.search_center_handler (
Callable[[tuple[float,float]],None]) – Callback invoked when the map center changes.tile_opacity (
float) – Base map tile opacity.kwargs – Forwarded to
PositionMap.
- click_result(rank, *, emit_action=True, recenter=True, show_details=True)¶
Programmatically simulate a map click on the result at rank.
This pushes an
ActionIntentto the queue and, when travel-time mode is active, draws the detour route for the clicked result.Example:
app.map_w.click_result(6)
- Return type:
None
- class here_search_demo.widgets.route.RouteController(map_instance, credentials, routing_api_call_handler=None)¶
Bases:
RouteDrawMixinRoute acquisition and rendering controller for map widgets.
The controller fetches route geometry, renders route overlays/markers, and exposes helpers used by notebooks and UI callbacks to update route start/stop/at positions and corridor width.
- Parameters:
map_instance (
PositionMap) – Map widget receiving route layers.credentials (
Credentials) – HERE credentials used for routing requests.
- property all_along: bool¶
Convenience property — reads
ranking_mode.all_along.
- clear_detour_routes()¶
Remove any rendered detour overlays without touching the route.
- property minimal_detour: bool¶
Convenience property — reads
ranking_mode.travel_time.
- on_drawn(callback)¶
Register callback to be called each time a route is fully drawn.
The callback receives this
RouteControllerinstance so it can inspectflexpolyline,waypoints_count,start_position, etc. Multiple callbacks may be registered; they are called in registration order.Example:
def my_handler(route): print(f"Route ready: {route.waypoints_count} waypoints") controller.on_drawn(my_handler)
- Return type:
None
- on_removed(callback)¶
Register callback to be called when a route is removed.
- Return type:
None
- property search_at_position: tuple[float, float] | None¶
Position sent as at= to the Search API.
When mins_from_pos > 0 this is the point that many minutes ahead of the origin along the route; otherwise it is the same as
current_position(the car marker location).
- set_current_position(latlon=None)¶
Set the current car position on the route.
- Parameters:
latlon (
tuple[float,float] |None) –(lat, lon)current position.
- set_mins_from_pos(mins)¶
Set X minutes ahead of the origin position as the new search centre.
- set_route_start(latlon)¶
Set the route origin marker and trigger route acquisition when complete.
- Parameters:
latlon (
tuple[float,float]) –(lat, lon)origin position.
- set_route_stop(latlon)¶
Set the route destination marker and trigger route acquisition when complete.
- Parameters:
latlon (
tuple[float,float]) –(lat, lon)destination position.
- set_route_width(width)¶
Set corridor width (meters) used for route geometry and rerender it.
- Parameters:
width (
int|None) – Corridor width in meters;Nonekeeps/defaults width.
- class here_search_demo.routing_api.RoutingAPI(credentials=None, cache=None, raise_for_status=True, options=None, log_fn=None, on_request_sent=None)¶
Bases:
objecthttps://www.here.com/docs/bundle/routing-api-v8-api-reference/page/index.html
- property api_key: str | None¶
Return the current API key from credentials.
- auth_headers(token)¶
Return HTTP request headers with the bearer token in the
Authorizationfield.- Parameters:
token (
str) – an OAuth2 access token- Return type:
dict- Returns:
authorization headers
- property credentials: Credentials¶
Return the credentials object.
- do_log(request, extra_columns=None)¶
Send a log entry for request to the configured sink, if any.
- Return type:
None
- get_x_headers(headers)¶
Extract the
X-*headers of a full headers mapping.- Return type:
dict
- static merge_sections(sections)¶
Combine consecutive sections into the single
RouteSectionof a leg.Durations and lengths are summed, geometries are concatenated (dropping the duplicated point shared by two consecutive sections) and span offsets are rebased onto the concatenated geometry.
- Parameters:
sections (
Sequence[RouteSection]) – consecutive sections belonging to the same leg- Return type:
- Returns:
one
RouteSectioncovering the whole leg
- static query(params)¶
Return params in the form expected by the runtime HTTP session.
lite.HTTPSessionencodes the query withdoseq=Trueand therefore accepts list values, whileaiohttprequires repeated two-tuples.- Return type:
Any
- 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
- async send(session, request)¶
Return the Routing API response for request, from the cache when possible.
- Parameters:
session (
ClientSession) – instance of HTTPSessionrequest (
Request) – Routing Request object
- Return type:
Response- Returns:
a Response object
- static split_at(sections, latitude, longitude)¶
Split sections into the legs before and after a via waypoint.
The boundary is the section end point closest to
(latitude, longitude), which makes the split immune to the extra sections the Routing API inserts on transport-mode changes (ferries, car trains, …).- Parameters:
sections (
Sequence[RouteSection]) – the sections of a route built with one via waypointlatitude (
float) – via waypoint latitudelongitude (
float) – via waypoint longitude
- Return type:
tuple[list[RouteSection],list[RouteSection]]- Returns:
the
(to_leg, from_leg)section groups
- class here_search_demo.routing_api.Waypoint(latitude, longitude, name_hint=None)¶
Bases:
objectA 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.routing_api.RouteSection(duration, length, polyline, spans=<factory>)¶
Bases:
objectOne
sections[]entry of a routing response.- Variables:
duration – travel duration in seconds
length – travel distance in meters
polyline – encoded flexible polyline of the section geometry
spans – the section
spans[]when they were requested
- class here_search_demo.routing_api.RoutingOptions(transport_mode='car', routing_mode='fast', return_fields=('summary', 'polyline'), spans=None)¶
Bases:
objectDefault request parameters of a
RoutingAPIinstance.- Variables:
transport_mode – value of the
transportModeparameterreturn_fields – values joined into the
returnparameterspans – values joined into the
spansparameter, orNone
- class here_search_demo.route_engine.RouteEngine(credentials, *, routing_api=None, on_routing_request=None, route_cache=None, width=100, retrieve_route_fn=None)¶
Bases:
objectHead-agnostic route state and routing retrieval service.
This class intentionally has no widget dependencies. It stores route/ranking state, computes derived search context, manages route cache, and retrieves route geometry through
RoutingAPI.
- class here_search_demo.ranking.RankingMode(all_along=False, travel_time=False)¶
Bases:
objectImmutable description of the current ranking configuration.
Parameters¶
- all_along:
When
Truethe Search API request includesranking=excursionDistanceso results are pre-sorted by proximity to the route on the server side.- travel_time:
When
Truethe client appliesDetourRankerto reorder results by actual driving time and annotate each item with detour polylines.
- property needs_client_rerank: bool¶
Whether the response requires client-side travel-time reranking.
- property needs_route_polyline: bool¶
Whether a route (corridor) must be sent with the search request.
- property server_ranking: str | None¶
Value for the
rankingrequest parameter, orNone.
- class here_search_demo.detour.DetourRanker(credentials, at_pos, stop_pos, on_routing_request=None, route_cache=None, routing_api=None)¶
Bases:
objectReranks 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
Route-stratified corridor (“all along the route”) search.
A plain ranking=excursionDistance corridor search ranks matches purely by
distance from the route, which can bunch every result near the start of a
long remaining trip. corridor_search() splits the remaining route
(from the search position to the destination) into equal-distance slices,
fires one corridor search per slice in parallel, and merges the results with
an equal-allocation, quota-redistributing selection so results spread across
the whole remaining journey instead of clustering at one end.
For short remaining routes (or no route at all) corridor_search() is a
no-op wrapper around a single call, identical to today’s behavior.
- here_search_demo.stratified_search.compute_slice_ranges(waypoints, n)¶
Partition waypoints into n contiguous, equal-distance
(start_idx, end_idx)ranges.Adjacent ranges share their boundary waypoint, so the resulting sub-polylines stay geometrically contiguous. If waypoints is too sparse to support n distinct ranges, trailing ranges degenerate to a single point rather than raising.
- Return type:
list[tuple[int,int]]
- async here_search_demo.stratified_search.corridor_search(*, context, limit, single_call, session, threshold_m=1000, max_slices=20)¶
Fetch up to limit corridor results, stratifying across route slices when worthwhile.
Falls back to a single
single_callinvocation (today’s behavior) whenall_alongranking isn’t requested, there is no route, the remaining route is too short to bother slicing, or the result count is too low (should_stratify()) to need spreading out. Stratification only helpsranking=excursionDistanceresults, which is the mode prone to bunching every result near one end of the route; default-relevance corridor searches are left untouched.- Return type:
Response
- here_search_demo.stratified_search.merge_with_quota_redistribution(per_slice_items, limit, dedup_key=<function <lambda>>)¶
Equal-allocation selection with adaptive quota redistribution.
Tier-synchronized round-robin: every slice’s best not-yet-picked candidate is taken before any slice’s 2nd-best, in route order, so an empty slice’s unused quota is redistributed across the other slices without favoring whichever slice happens to have the most backup candidates. Duplicate ids are skipped in place (pulling that slice’s next buffered candidate) rather than dropping the slot. Stops once limit is reached or a full pass makes no progress (fewer than limit results is then accepted rather than issuing extra requests).
Returns
(slice_index, item)pairs sorted by slice_index (route order), with items from the same slice kept in their original (quality) order.- Return type:
list[tuple[int,dict]]
- here_search_demo.stratified_search.should_stratify(remaining_length_m, limit, threshold_m=1000)¶
Whether a corridor search over remaining_length_m metres should be split into slices.
- Return type:
bool
Pure-geometry helpers for route operations.
build_corridor computes a metre-accurate buffer polygon around a route
polyline using a local tangent-plane projection implemented with the Python
standard library, avoiding heavy numpy/pyproj runtime dependencies.
simplify_polyline reduces a polyline to a maximum number of points using a
GEOS Douglas–Peucker simplification.
- async here_search_demo.widgets.route_geometry.build_corridor(points, width)¶
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.
- here_search_demo.widgets.route_geometry.elapsed_sec_at_position(spans, waypoints, lat, lon)¶
Return the elapsed seconds from the route start to the waypoint closest to
(lat, lon).Each span dict must contain
offset(int) andduration(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 tospans[i + 1]['offset'](the last waypoint for the last span).- Return type:
float
- here_search_demo.widgets.route_geometry.haversine_m(lat1, lon1, lat2, lon2)¶
Great-circle distance in metres between two
(lat, lon)points.- Return type:
float
- here_search_demo.widgets.route_geometry.position_at_x_sec_ahead(spans, waypoints, elapsed, x_sec)¶
Return the
(lat, lon)that isx_secseconds ahead ofelapsedalong the route.If the target is beyond the end of the route the final waypoint is returned.
- Return type:
tuple[float,float]
- here_search_demo.widgets.route_geometry.simplify_polyline(points, max_points, iterations=15)¶
Reduce
pointsto at mostmax_pointsusing GEOS Douglas–Peucker.- Return type:
list[tuple[float,float]]
- class here_search_demo.widgets.output_json.SearchResultJson(state=None, **kwargs)¶
Bases:
SearchResultList
- class here_search_demo.widgets.output_buttons.SearchResultButtons(widget=None, max_results_number=None, queue=None, state=None, on_result_click=None, layout=None, **kwargs)¶
Bases:
VBox
- class here_search_demo.entity.place.PlaceTaxonomyExample¶
Bases:
object
- class here_search_demo.entity.request.Request(endpoint=None, base_url=None, params=None, data=None, x_headers=None, previous_response=None)¶
Bases:
objectNormalized HERE Search request payload.
- Variables:
endpoint – target HERE Search endpoint enum
base_url – endpoint base URL
params – query-string parameters
data – optional request body (used for POST route payloads)
x_headers – optional request-scoped
X-*headersprevious_response – optional previous response used for follow-up flows
- property full¶
Return full request URL including encoded query string.
Multi-valued parameters (for instance the Routing API repeated
via) are encoded as repeated key/value pairs.- Returns:
full request URL
- property key: str¶
Return a deterministic cache key for this request.
- Returns:
cache key string derived from base URL and params
- class here_search_demo.entity.endpoint.Endpoint(*values)¶
Bases:
IntEnum
- class here_search_demo.entity.intent.ActionIntent(materialization, time)¶
Bases:
objectIntent emitted when the user clicks a result button for a LocationResponseItem.
Unlike
SearchIntent(kind="details"), this intent only triggers a signals call — no lookup is performed.