Skip to content
This repository has been archived by the owner on Sep 5, 2023. It is now read-only.

add autosuggest api #19

Merged
merged 5 commits into from
Aug 20, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
142 changes: 142 additions & 0 deletions docs/notebooks/autosuggest.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"source": [
"import os\n",
"os.environ[\"LS_API_KEY\"] = \"MY-API-KEY\" # replace your API key here."
],
"outputs": [],
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 14,
"source": [
"import os\n",
"\n",
"from here_location_services import LS\n",
"\n",
"LS_API_KEY = os.environ.get(\"LS_API_KEY\") # Get API KEY from environment.\n",
"ls = LS(api_key=LS_API_KEY)\n",
"\n",
"autosuggest_response = ls.autosuggest(\n",
" query=\"bar\",\n",
" limit=5,\n",
" at=[\"-13.163068,-72.545128\"],\n",
" terms_limit=3,\n",
")\n",
"\n",
"print(\"Query Items:\")\n",
"for item in autosuggest_response.queryTerms:\n",
" print(item)\n",
"\n",
"print(\"Search Items:\")\n",
"for item in autosuggest_response.items:\n",
" print(item)"
],
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Query Items:\n",
"{'term': 'Barceló', 'replaces': 'bar', 'start': 0, 'end': 3}\n",
"{'term': 'Bardot', 'replaces': 'bar', 'start': 0, 'end': 3}\n",
"{'term': 'Barista', 'replaces': 'bar', 'start': 0, 'end': 3}\n",
"Search Items:\n",
"{'title': 'bar', 'id': 'here:cm:ontology:bar_pub', 'resultType': 'categoryQuery', 'href': 'https://autosuggest.search.hereapi.com/v1/discover?q=bar&_ontology=bar_pub&at=-13.16307%2C-72.54513', 'highlights': {'title': [{'start': 0, 'end': 3}]}}\n",
"{'title': 'El Mirador - Snack Bar', 'id': 'here:pds:place:6046msmj-b110bba85a894aca85bda8a5f8639bd9', 'resultType': 'place', 'address': {'label': 'El Mirador - Snack Bar, Carretera Hiram Bingham, 08680 Machu Picchu, Perú'}, 'position': {'lat': -13.16579, 'lng': -72.54314}, 'access': [{'lat': -13.16578, 'lng': -72.54315}], 'distance': 371, 'categories': [{'id': '100-1000-0001', 'name': 'Restaurante informal', 'primary': True}, {'id': '100-1000-0000', 'name': 'Restaurante'}], 'highlights': {'title': [{'start': 19, 'end': 22}], 'address': {'label': [{'start': 19, 'end': 22}]}}}\n",
"{'title': 'Bar Pisco Brothers', 'id': 'here:pds:place:6046msmj-f80954cdf3b644389d0072d758d63210', 'resultType': 'place', 'address': {'label': 'Bar Pisco Brothers, Avenida Wakanki, 08681 Machu Picchu, Perú'}, 'position': {'lat': -13.15607, 'lng': -72.52229}, 'access': [{'lat': -13.15614, 'lng': -72.52241}], 'distance': 2593, 'categories': [{'id': '200-2000-0011', 'name': 'Bar o pub', 'primary': True}], 'highlights': {'title': [{'start': 0, 'end': 3}], 'address': {'label': [{'start': 0, 'end': 3}]}}}\n",
"{'title': \"Bar & Snack Tortu's\", 'id': 'here:pds:place:6046msmj-1df092f0321242b992e8636c412962c0', 'resultType': 'place', 'address': {'label': \"Bar & Snack Tortu's, Calle Aymuraypa Tikan, 08681 Machu Picchu, Perú\"}, 'position': {'lat': -13.15571, 'lng': -72.52318}, 'access': [{'lat': -13.15585, 'lng': -72.52315}], 'distance': 2514, 'categories': [{'id': '200-2000-0011', 'name': 'Bar o pub', 'primary': True}], 'highlights': {'title': [{'start': 0, 'end': 3}], 'address': {'label': [{'start': 0, 'end': 3}]}}}\n",
"{'title': 'Barnim (BAR), Brandenburg, Deutschland', 'id': 'here:cm:namedplace:20187485', 'resultType': 'administrativeArea', 'administrativeAreaType': 'county', 'address': {'label': 'Barnim, Brandenburg, Deutschland'}, 'position': {'lat': 52.83392, 'lng': 13.81271}, 'distance': 10928834, 'mapView': {'west': 13.37457, 'south': 52.54565, 'east': 14.15673, 'north': 53.05861}, 'highlights': {'title': [], 'address': {'label': []}}}\n"
]
}
],
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 18,
"source": [
"from here_map_widget import Map, Marker, Group\n",
"\n",
"results = []\n",
"for item in autosuggest_response.items:\n",
" if item[\"resultType\"] == \"place\":\n",
" results.append(\n",
" Marker(\n",
" lat=item[\"position\"][\"lat\"],\n",
" lng=item[\"position\"][\"lng\"],\n",
" data=item[\"title\"],\n",
" )\n",
" )\n",
"group = Group(volatility=True)\n",
"group.add_objects(results)\n",
"m = Map(\n",
" api_key=LS_API_KEY,\n",
" center=[-13.163068,-72.545128],\n",
" zoom=14,\n",
")\n",
"m.add_object(group)\n",
"m"
],
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Markers placed: 3\n"
]
},
{
"output_type": "display_data",
"data": {
"text/plain": [
"Map(api_key='TKURWbpJHcbzmWMrmTZwGAdSTLrX8WY1oddj4S4U-EM', basemap=None, center=[-13.163068, -72.545128], obje…"
],
"application/vnd.jupyter.widget-view+json": {
"version_major": 2,
"version_minor": 0,
"model_id": "35877ce533064bf0a88e5cb48f5ded91"
}
},
"metadata": {}
}
],
"metadata": {}
},
{
"cell_type": "code",
"execution_count": null,
"source": [],
"outputs": [],
"metadata": {}
}
],
"metadata": {
"orig_nbformat": 4,
"language_info": {
"name": "python",
"version": "3.9.6",
"mimetype": "text/x-python",
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"pygments_lexer": "ipython3",
"nbconvert_exporter": "python",
"file_extension": ".py"
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3.9.6 64-bit"
},
"interpreter": {
"hash": "aee8b7b246df8f9039afb4144a1f6fd8d2ca17a180786b69acc140d282b71a49"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
69 changes: 69 additions & 0 deletions docs/source/autosuggest.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
Autosuggest
===============
`Autosuggest endpoint of HERE Geocoding & Search API <https://developer.here.com/documentation/geocoding-search-api/dev_guide/topics/endpoint-autosuggest-brief.html>`_ improves the user's search experience by allowing submittal of free-form, incomplete and misspelled addresses or place names to the endpoint.

Example
-------

.. jupyter-execute::

import os

from here_location_services import LS
from here_map_widget import Map, Marker, Group

LS_API_KEY = os.environ.get("LS_API_KEY") # Get API KEY from environment.
ls = LS(api_key=LS_API_KEY)

autosuggest_response = ls.autosuggest(
query="bar",
limit=5,
at=["-13.163068,-72.545128"],
terms_limit=3,
)

print("Query Items:")
for item in autosuggest_response.queryTerms:
print(item)

print("Search Items:")
for item in autosuggest_response.items:
print(item)

results = []
for item in autosuggest_response.items:
if item["resultType"] == "place":
results.append(
Marker(
lat=item["position"]["lat"],
lng=item["position"]["lng"],
data=item["title"],
)
)
group = Group(volatility=True)
group.add_objects(results)
m = Map(
api_key=LS_API_KEY,
center=[-13.163068,-72.545128],
zoom=14,
)
m.add_object(group)
m

Attributes
----------

==================== ======================================================================================= ===
Attribute Type Doc
==================== ======================================================================================= ===
query string A string for free-text query. Example: `res`, `rest`
at list optional Specify the center of the search context expressed as list of coordinates. One of `at`, `search_in_circle` or `search_in_bbox` is required. Parameters "at", "search_in_circle" and "search_in_bbox" are mutually exclusive. Only one of them is allowed.
search_in_circle :class:`SearchCircle <here_location_services.config.autosuggest_config.SearchCircle>` optional Search within a circular geographic area provided as latitude, longitude, and radius (in meters)
search_in_bbox tuple optional Search within a rectangular bounding box geographic area provided as tuple of west longitude, south latitude, east longitude, north latitude
in_country list optional Search within a specific or multiple countries provided as comma-separated ISO 3166-1 alpha-3 country codes. The country codes are to be provided in all uppercase. Must be accompanied by exactly one of `at`, `search_in_circle` or `search_in_bbox`.
limit int optional An integer specifiying maximum number of results to be returned.
terms_limit int optional An integer specifiying maximum number of Query Terms Suggestions to be returned.
lang list optional List of strings to select the language to be used for result rendering from a list of BCP 47 compliant language codes.
political_view string optional Toggle the political view by passing a string from :attr:`POLITICAL_VIEW <here_location_services.config.autosuggest_config.POLITICAL_VIEW>`.
show list optional Select additional fields from :attr:`SHOW <here_location_services.config.autosuggest_config.SHOW>`. to be rendered in the response.
==================== ======================================================================================= ===
8 changes: 8 additions & 0 deletions docs/source/here_location_services.autosuggest_api.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
here\_location\_services.autosuggest\_api module
================================================

.. automodule:: here_location_services.autosuggest_api
:members:
:undoc-members:
:show-inheritance:
:private-members:
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
here\_location\_services.config.autosuggest\_config module
==========================================================

.. automodule:: here_location_services.config.autosuggest_config
:members:
:undoc-members:
:show-inheritance:
:private-members:
1 change: 1 addition & 0 deletions docs/source/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ A Python client for `HERE Location Services`_.
Discover <discover>
Browse <browse>
Lookup <lookup>
Autosugggest <autosuggest>

.. toctree::
:maxdepth: 1
Expand Down
104 changes: 104 additions & 0 deletions here_location_services/autosuggest_api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
# Copyright (C) 2019-2021 HERE Europe B.V.
# SPDX-License-Identifier: Apache-2.0

"""This module contains classes for accessing `HERE Autosuggest API <https://developer.here.com/documentation/geocoding-search-api/dev_guide/topics/endpoint-autosuggest-brief.html>`_.
""" # noqa E501

from typing import Dict, List, Optional, Tuple

from here_location_services.config.autosuggest_config import SearchCircle
from here_location_services.platform.auth import Auth

from .apis import Api
from .exceptions import ApiError


class AutosuggestApi(Api):
"""A class for accessing HERE Autosuggest API."""

def __init__(
self,
api_key: Optional[str] = None,
auth: Optional[Auth] = None,
proxies: Optional[dict] = None,
country: str = "row",
):
super().__init__(api_key, auth=auth, proxies=proxies, country=country)
self._base_url = f"https://autosuggest.search.{self._get_url_string()}"

def get_autosuggest(
self,
query: str,
at: Optional[List] = None,
jain-aayush1123 marked this conversation as resolved.
Show resolved Hide resolved
search_in_circle: Optional[SearchCircle] = None,
search_in_bbox: Optional[Tuple] = None,
in_country: Optional[List[str]] = None,
limit: Optional[int] = 20,
terms_limit: Optional[int] = None,
lang: Optional[List[str]] = None,
political_view: Optional[str] = None,
show: Optional[List[str]] = None,
):
"""Suggest address or place candidates based on an incomplete or misspelled query

:param query: A string for free-text query. Example: res, rest
:param at: Specify the center of the search context expressed as list of coordinates
One of `at`, `search_in_circle` or `search_in_bbox` is required.
Parameters "at", "search_in_circle" and "search_in_bbox" are mutually exclusive. Only
one of them is allowed.
:param search_in_circle: Search within a circular geographic area provided as
latitude, longitude, and radius (in meters)
:param search_in_bbox: Search within a rectangular bounding box geographic area provided
as tuple of west longitude, south latitude, east longitude, north latitude
:param in_country: Search within a specific or multiple countries provided as
comma-separated ISO 3166-1 alpha-3 country codes. The country codes are to be
provided in all uppercase. Must be accompanied by exactly one of
`at`, `search_in_circle` or `search_in_bbox`.
:param limit: An integer specifiying maximum number of results to be returned.
:param terms_limit: An integer specifiying maximum number of Query Terms Suggestions
to be returned.
:param lang: List of strings to select the language to be used for result rendering
from a list of BCP 47 compliant language codes.
:param political_view: Toggle the political view.
:param show: Select additional fields to be rendered in the response. Please note
that some of the fields involve additional webservice calls and can increase
the overall response time.
:return: :class:`requests.Response` object.
:raises ApiError: If ``status_code`` of API response is not 200.

"""
path = "v1/autosuggest"
url = f"{self._base_url}/{path}"
params: Dict[str, str] = {
"q": query,
}
if at:
params["at"] = ",".join([str(i) for i in at])
if in_country:
params["in"] = "countryCode:" + ",".join([str(i) for i in in_country])
if search_in_circle:
params["in"] = (
"circle:"
+ str(search_in_circle.lat)
+ ","
+ str(search_in_circle.lng)
+ ";r="
+ str(search_in_circle.radius)
)
if limit:
params["limit"] = str(limit)
if terms_limit:
params["termsLimit"] = str(terms_limit)
if lang:
params["lang"] = ",".join([str(i) for i in lang])
if political_view:
params["politicalView"] = political_view
if show:
params["show"] = ",".join([str(i) for i in show])
if search_in_bbox:
params["in"] = "bbox:" + ",".join([str(i) for i in search_in_bbox])
resp = self.get(url, params=params, proxies=self.proxies)
if resp.status_code == 200:
return resp
else:
raise ApiError(resp)
Loading