1 # SPDX-License-Identifier: GPL-2.0-only
3 # This file is part of Nominatim. (https://nominatim.org)
5 # Copyright (C) 2023 by the Nominatim developer community.
6 # For a full list of authors see the git log.
8 Implementation of classes for API access via libraries.
10 from typing import Mapping, Optional, Any, AsyncIterator, Dict, Sequence, List, Tuple
14 from pathlib import Path
16 import sqlalchemy as sa
17 import sqlalchemy.ext.asyncio as sa_asyncio
19 from nominatim.errors import UsageError
20 from nominatim.db.sqlalchemy_schema import SearchTables
21 from nominatim.db.async_core_library import PGCORE_LIB, PGCORE_ERROR
22 from nominatim.config import Configuration
23 from nominatim.api.connection import SearchConnection
24 from nominatim.api.status import get_status, StatusResult
25 from nominatim.api.lookup import get_detailed_place, get_simple_place
26 from nominatim.api.reverse import ReverseGeocoder
27 from nominatim.api.search import ForwardGeocoder, Phrase, PhraseType, make_query_analyzer
28 import nominatim.api.types as ntyp
29 from nominatim.api.results import DetailedResult, ReverseResult, SearchResults
32 class NominatimAPIAsync:
33 """ The main frontend to the Nominatim database implements the
34 functions for lookup, forward and reverse geocoding using
35 asynchronous functions.
37 This class shares most of the functions with its synchronous
38 version. There are some additional functions or parameters,
39 which are documented below.
41 def __init__(self, project_dir: Path,
42 environ: Optional[Mapping[str, str]] = None,
43 loop: Optional[asyncio.AbstractEventLoop] = None) -> None:
44 """ Initiate a new frontend object with synchronous API functions.
47 project_dir: Path to the
48 [project directory](../admin/Import.md#creating-the-project-directory)
49 of the local Nominatim installation.
50 environ: Mapping of [configuration parameters](../customize/Settings.md).
51 When set, replaces any configuration via environment variables.
52 Settings in this mapping also have precedence over any
53 parameters found in the `.env` file of the project directory.
54 loop: The asyncio event loop that will be used when calling
55 functions. Only needed, when a custom event loop is used
56 and the Python version is 3.9 or earlier.
58 self.config = Configuration(project_dir, environ)
59 self.query_timeout = self.config.get_int('QUERY_TIMEOUT') \
60 if self.config.QUERY_TIMEOUT else None
61 self.server_version = 0
63 if sys.version_info >= (3, 10):
64 self._engine_lock = asyncio.Lock()
66 self._engine_lock = asyncio.Lock(loop=loop) # pylint: disable=unexpected-keyword-arg
67 self._engine: Optional[sa_asyncio.AsyncEngine] = None
68 self._tables: Optional[SearchTables] = None
69 self._property_cache: Dict[str, Any] = {'DB:server_version': 0}
72 async def setup_database(self) -> None:
73 """ Set up the SQL engine and connections.
75 This function will be implicitly called when the database is
76 accessed for the first time. You may also call it explicitly to
77 avoid that the first call is delayed by the setup.
79 async with self._engine_lock:
83 dsn = self.config.get_database_params()
84 pool_size = self.config.get_int('API_POOL_SIZE')
86 query = {k: v for k, v in dsn.items()
87 if k not in ('user', 'password', 'dbname', 'host', 'port')}
89 dburl = sa.engine.URL.create(
90 f'postgresql+{PGCORE_LIB}',
91 database=dsn.get('dbname'),
92 username=dsn.get('user'), password=dsn.get('password'),
93 host=dsn.get('host'), port=int(dsn['port']) if 'port' in dsn else None,
95 engine = sa_asyncio.create_async_engine(dburl, future=True,
96 max_overflow=0, pool_size=pool_size,
97 echo=self.config.get_bool('DEBUG_SQL'))
100 async with engine.begin() as conn:
101 result = await conn.scalar(sa.text('SHOW server_version_num'))
102 server_version = int(result)
103 except (PGCORE_ERROR, sa.exc.OperationalError):
106 if server_version >= 110000:
107 @sa.event.listens_for(engine.sync_engine, "connect")
108 def _on_connect(dbapi_con: Any, _: Any) -> None:
109 cursor = dbapi_con.cursor()
110 cursor.execute("SET jit_above_cost TO '-1'")
111 cursor.execute("SET max_parallel_workers_per_gather TO '0'")
112 # Make sure that all connections get the new settings
115 self._property_cache['DB:server_version'] = server_version
117 self._tables = SearchTables(sa.MetaData(), engine.name) # pylint: disable=no-member
118 self._engine = engine
121 async def close(self) -> None:
122 """ Close all active connections to the database. The NominatimAPIAsync
123 object remains usable after closing. If a new API functions is
124 called, new connections are created.
126 if self._engine is not None:
127 await self._engine.dispose()
130 @contextlib.asynccontextmanager
131 async def begin(self) -> AsyncIterator[SearchConnection]:
132 """ Create a new connection with automatic transaction handling.
134 This function may be used to get low-level access to the database.
135 Refer to the documentation of SQLAlchemy for details how to use
136 the connection object.
138 if self._engine is None:
139 await self.setup_database()
141 assert self._engine is not None
142 assert self._tables is not None
144 async with self._engine.begin() as conn:
145 yield SearchConnection(conn, self._tables, self._property_cache)
148 async def status(self) -> StatusResult:
149 """ Return the status of the database.
152 async with self.begin() as conn:
153 conn.set_query_timeout(self.query_timeout)
154 status = await get_status(conn)
155 except (PGCORE_ERROR, sa.exc.OperationalError):
156 return StatusResult(700, 'Database connection failed')
161 async def details(self, place: ntyp.PlaceRef, **params: Any) -> Optional[DetailedResult]:
162 """ Get detailed information about a place in the database.
164 Returns None if there is no entry under the given ID.
166 details = ntyp.LookupDetails.from_kwargs(params)
167 async with self.begin() as conn:
168 conn.set_query_timeout(self.query_timeout)
170 await make_query_analyzer(conn)
171 return await get_detailed_place(conn, place, details)
174 async def lookup(self, places: Sequence[ntyp.PlaceRef], **params: Any) -> SearchResults:
175 """ Get simple information about a list of places.
177 Returns a list of place information for all IDs that were found.
179 details = ntyp.LookupDetails.from_kwargs(params)
180 async with self.begin() as conn:
181 conn.set_query_timeout(self.query_timeout)
183 await make_query_analyzer(conn)
184 return SearchResults(filter(None,
185 [await get_simple_place(conn, p, details) for p in places]))
188 async def reverse(self, coord: ntyp.AnyPoint, **params: Any) -> Optional[ReverseResult]:
189 """ Find a place by its coordinates. Also known as reverse geocoding.
191 Returns the closest result that can be found or None if
192 no place matches the given criteria.
194 # The following negation handles NaN correctly. Don't change.
195 if not abs(coord[0]) <= 180 or not abs(coord[1]) <= 90:
196 # There are no results to be expected outside valid coordinates.
199 details = ntyp.ReverseDetails.from_kwargs(params)
200 async with self.begin() as conn:
201 conn.set_query_timeout(self.query_timeout)
203 await make_query_analyzer(conn)
204 geocoder = ReverseGeocoder(conn, details)
205 return await geocoder.lookup(coord)
208 async def search(self, query: str, **params: Any) -> SearchResults:
209 """ Find a place by free-text search. Also known as forward geocoding.
211 query = query.strip()
213 raise UsageError('Nothing to search for.')
215 async with self.begin() as conn:
216 conn.set_query_timeout(self.query_timeout)
217 geocoder = ForwardGeocoder(conn, ntyp.SearchDetails.from_kwargs(params),
218 self.config.get_int('REQUEST_TIMEOUT') \
219 if self.config.REQUEST_TIMEOUT else None)
220 phrases = [Phrase(PhraseType.NONE, p.strip()) for p in query.split(',')]
221 return await geocoder.lookup(phrases)
224 # pylint: disable=too-many-arguments,too-many-branches
225 async def search_address(self, amenity: Optional[str] = None,
226 street: Optional[str] = None,
227 city: Optional[str] = None,
228 county: Optional[str] = None,
229 state: Optional[str] = None,
230 country: Optional[str] = None,
231 postalcode: Optional[str] = None,
232 **params: Any) -> SearchResults:
233 """ Find an address using structured search.
235 async with self.begin() as conn:
236 conn.set_query_timeout(self.query_timeout)
237 details = ntyp.SearchDetails.from_kwargs(params)
239 phrases: List[Phrase] = []
242 phrases.append(Phrase(PhraseType.AMENITY, amenity))
244 phrases.append(Phrase(PhraseType.STREET, street))
246 phrases.append(Phrase(PhraseType.CITY, city))
248 phrases.append(Phrase(PhraseType.COUNTY, county))
250 phrases.append(Phrase(PhraseType.STATE, state))
252 phrases.append(Phrase(PhraseType.POSTCODE, postalcode))
254 phrases.append(Phrase(PhraseType.COUNTRY, country))
257 raise UsageError('Nothing to search for.')
259 if amenity or street:
260 details.restrict_min_max_rank(26, 30)
262 details.restrict_min_max_rank(13, 25)
264 details.restrict_min_max_rank(10, 12)
266 details.restrict_min_max_rank(5, 9)
268 details.restrict_min_max_rank(5, 11)
270 details.restrict_min_max_rank(4, 4)
272 if 'layers' not in params:
273 details.layers = ntyp.DataLayer.ADDRESS
275 details.layers |= ntyp.DataLayer.POI
277 geocoder = ForwardGeocoder(conn, details,
278 self.config.get_int('REQUEST_TIMEOUT') \
279 if self.config.REQUEST_TIMEOUT else None)
280 return await geocoder.lookup(phrases)
283 async def search_category(self, categories: List[Tuple[str, str]],
284 near_query: Optional[str] = None,
285 **params: Any) -> SearchResults:
286 """ Find an object of a certain category near another place.
287 The near place may either be given as an unstructured search
288 query in itself or as coordinates.
291 return SearchResults()
293 details = ntyp.SearchDetails.from_kwargs(params)
294 async with self.begin() as conn:
295 conn.set_query_timeout(self.query_timeout)
297 phrases = [Phrase(PhraseType.NONE, p) for p in near_query.split(',')]
301 await make_query_analyzer(conn)
303 geocoder = ForwardGeocoder(conn, details,
304 self.config.get_int('REQUEST_TIMEOUT') \
305 if self.config.REQUEST_TIMEOUT else None)
306 return await geocoder.lookup_pois(categories, phrases)
311 """ This class provides a thin synchronous wrapper around the asynchronous
312 Nominatim functions. It creates its own event loop and runs each
313 synchronous function call to completion using that loop.
316 def __init__(self, project_dir: Path,
317 environ: Optional[Mapping[str, str]] = None) -> None:
318 """ Initiate a new frontend object with synchronous API functions.
321 project_dir: Path to the
322 [project directory](../admin/Import.md#creating-the-project-directory)
323 of the local Nominatim installation.
324 environ: Mapping of [configuration parameters](../customize/Settings.md).
325 When set, replaces any configuration via environment variables.
326 Settings in this mapping also have precedence over any
327 parameters found in the `.env` file of the project directory.
329 self._loop = asyncio.new_event_loop()
330 self._async_api = NominatimAPIAsync(project_dir, environ, loop=self._loop)
333 def close(self) -> None:
334 """ Close all active connections to the database.
336 This function also closes the asynchronous worker loop making
337 the NominatimAPI object unusuable.
339 self._loop.run_until_complete(self._async_api.close())
344 def config(self) -> Configuration:
345 """ Provide read-only access to the [configuration](#Configuration)
348 return self._async_api.config
350 def status(self) -> StatusResult:
351 """ Return the status of the database as a dataclass object
352 with the fields described below.
355 status(int): A status code as described on the status page.
356 message(str): Either 'OK' or a human-readable message of the
358 software_version(tuple): A tuple with the version of the
359 Nominatim library consisting of (major, minor, patch, db-patch)
361 database_version(tuple): A tuple with the version of the library
362 which was used for the import or last migration.
363 Also consists of (major, minor, patch, db-patch).
364 data_updated(datetime): Timestamp with the age of the data.
366 return self._loop.run_until_complete(self._async_api.status())
369 def details(self, place: ntyp.PlaceRef, **params: Any) -> Optional[DetailedResult]:
370 """ Get detailed information about a place in the database.
372 The result is a dataclass object with the fields described below
373 or `None` if the place could not be found in the database.
376 place: Description of the place to look up. See
377 [Place identification](Input-Parameter-Types.md#place-identification)
378 for the various ways to reference a place.
381 geometry_output (enum): Add the full geometry of the place to the result.
382 Multiple formats may be selected. Note that geometries can become
383 quite large. (Default: none)
384 geometry_simplification (float): Simplification factor to use on
385 the geometries before returning them. The factor expresses
386 the tolerance in degrees from which the geometry may differ.
387 Topology is preserved. (Default: 0.0)
388 address_details (bool): Add detailed information about the places
389 that make up the address of the requested object. (Default: False)
390 linked_places (bool): Add detailed information about the places
391 that link to the result. (Default: False)
392 parented_places (bool): Add detailed information about all places
393 for which the requested object is a parent, i.e. all places for
394 which the object provides the address details.
395 Only POI places can have parents. (Default: False)
396 keywords (bool): Add detailed information about the search terms
400 source_table (enum): Data source of the place. See below for possible values.
401 category (tuple): A tuple of two strings with the primary OSM tag
403 centroid (Point): Point position of the place.
404 place_id (Optional[int]): Internal ID of the place. This ID may differ
405 for the same place between different installations.
406 parent_place_id (Optional(int]): Internal ID of the parent of this
407 place. Only meaning full for POI-like objects (places with a
409 linked_place_id (Optional[int]): Internal ID of the place this object
410 linkes to. When this ID is set then there is no guarantee that
411 the rest of the result information is complete.
412 admin_level (int): Value of the `admin_level` OSM tag. Only meaningful
413 for administrative boundary objects.
414 indexed_date (datetime): Timestamp when the place was last updated.
415 osm_object (Optional[tuple]): OSM type and ID of the place, if available.
416 names (Optional[dict]): Dictionary of names of the place. Keys are
417 usually the corresponding OSM tag keys.
418 address (Optional[dict]): Dictionary of address parts directly
419 attributed to the place. Keys are usually the corresponding
420 OSM tag keys with the `addr:` prefix removed.
421 extratags (Optional[dict]): Dictionary of additional attributes for
422 the place. Usually OSM tag keys and values.
423 housenumber (Optional[str]): House number of the place, normalised
424 for lookup. To get the house number in its original spelling,
425 use `address['housenumber']`.
426 postcode (Optional[str]): Computed postcode for the place. To get
427 directly attributed postcodes, use `address['postcode']` instead.
428 wikipedia (Optional[str]): Reference to a wikipedia site for the place.
429 The string has the format <language code>:<wikipedia title>.
430 rank_address (int): [Address rank](../customize/Ranking.md#address-rank).
431 rank_search (int): [Search rank](../customize/Ranking.md#search-rank).
432 importance (Optional[float]): Relative importance of the place. This is a measure
433 how likely the place will be searched for.
434 country_code (Optional[str]): Country the feature is in as
435 ISO 3166-1 alpha-2 country code.
436 address_rows (Optional[AddressLines]): List of places that make up the
437 computed address. `None` when `address_details` parameter was False.
438 linked_rows (Optional[AddressLines]): List of places that link to the object.
439 `None` when `linked_places` parameter was False.
440 parented_rows (Optional[AddressLines]): List of direct children of the place.
441 `None` when `parented_places` parameter was False.
442 name_keywords (Optional[WordInfos]): List of search words for the name of
443 the place. `None` when `keywords` parameter is set to False.
444 address_keywords (Optional[WordInfos]): List of search word for the address of
445 the place. `None` when `keywords` parameter is set to False.
446 geometry (dict): Dictionary containing the full geometry of the place
447 in the formats requested in the `geometry_output` parameter.
449 return self._loop.run_until_complete(self._async_api.details(place, **params))
452 def lookup(self, places: Sequence[ntyp.PlaceRef], **params: Any) -> SearchResults:
453 """ Get simple information about a list of places.
455 Returns a list of place information for all IDs that were found.
456 Each result is a dataclass with the fields detailed below.
459 places: List of descriptions of the place to look up. See
460 [Place identification](Input-Parameter-Types.md#place-identification)
461 for the various ways to reference a place.
464 geometry_output (enum): Add the full geometry of the place to the result.
465 Multiple formats may be selected. Note that geometries can become
466 quite large. (Default: none)
467 geometry_simplification (float): Simplification factor to use on
468 the geometries before returning them. The factor expresses
469 the tolerance in degrees from which the geometry may differ.
470 Topology is preserved. (Default: 0.0)
471 address_details (bool): Add detailed information about the places
472 that make up the address of the requested object. (Default: False)
473 linked_places (bool): Add detailed information about the places
474 that link to the result. (Default: False)
475 parented_places (bool): Add detailed information about all places
476 for which the requested object is a parent, i.e. all places for
477 which the object provides the address details.
478 Only POI places can have parents. (Default: False)
479 keywords (bool): Add detailed information about the search terms
483 source_table (enum): Data source of the place. See below for possible values.
484 category (tuple): A tuple of two strings with the primary OSM tag
486 centroid (Point): Point position of the place.
487 place_id (Optional[int]): Internal ID of the place. This ID may differ
488 for the same place between different installations.
489 osm_object (Optional[tuple]): OSM type and ID of the place, if available.
490 names (Optional[dict]): Dictionary of names of the place. Keys are
491 usually the corresponding OSM tag keys.
492 address (Optional[dict]): Dictionary of address parts directly
493 attributed to the place. Keys are usually the corresponding
494 OSM tag keys with the `addr:` prefix removed.
495 extratags (Optional[dict]): Dictionary of additional attributes for
496 the place. Usually OSM tag keys and values.
497 housenumber (Optional[str]): House number of the place, normalised
498 for lookup. To get the house number in its original spelling,
499 use `address['housenumber']`.
500 postcode (Optional[str]): Computed postcode for the place. To get
501 directly attributed postcodes, use `address['postcode']` instead.
502 wikipedia (Optional[str]): Reference to a wikipedia site for the place.
503 The string has the format <language code>:<wikipedia title>.
504 rank_address (int): [Address rank](../customize/Ranking.md#address-rank).
505 rank_search (int): [Search rank](../customize/Ranking.md#search-rank).
506 importance (Optional[float]): Relative importance of the place. This is a measure
507 how likely the place will be searched for.
508 country_code (Optional[str]): Country the feature is in as
509 ISO 3166-1 alpha-2 country code.
510 address_rows (Optional[AddressLines]): List of places that make up the
511 computed address. `None` when `address_details` parameter was False.
512 linked_rows (Optional[AddressLines]): List of places that link to the object.
513 `None` when `linked_places` parameter was False.
514 parented_rows (Optional[AddressLines]): List of direct children of the place.
515 `None` when `parented_places` parameter was False.
516 name_keywords (Optional[WordInfos]): List of search words for the name of
517 the place. `None` when `keywords` parameter is set to False.
518 address_keywords (Optional[WordInfos]): List of search word for the address of
519 the place. `None` when `keywords` parameter is set to False.
520 bbox (Bbox): Bounding box of the full geometry of the place.
521 If the place is a single point, then the size of the bounding
522 box is guessed according to the type of place.
523 geometry (dict): Dictionary containing the full geometry of the place
524 in the formats requested in the `geometry_output` parameter.
526 return self._loop.run_until_complete(self._async_api.lookup(places, **params))
529 def reverse(self, coord: ntyp.AnyPoint, **params: Any) -> Optional[ReverseResult]:
530 """ Find a place by its coordinates. Also known as reverse geocoding.
532 Returns the closest result that can be found or `None` if
533 no place matches the given criteria. The result is a dataclass
534 with the fields as detailed below.
537 coord: Coordinate to lookup the place for as a Point
538 or a tuple (x, y). Must be in WGS84 projection.
541 max_rank (int): Highest address rank to return. Can be used to
542 restrict search to streets or settlements.
543 layers (enum): Defines the kind of data to take into account.
544 See description of layers below. (Default: addresses and POIs)
545 geometry_output (enum): Add the full geometry of the place to the result.
546 Multiple formats may be selected. Note that geometries can become
547 quite large. (Default: none)
548 geometry_simplification (float): Simplification factor to use on
549 the geometries before returning them. The factor expresses
550 the tolerance in degrees from which the geometry may differ.
551 Topology is preserved. (Default: 0.0)
552 address_details (bool): Add detailed information about the places
553 that make up the address of the requested object. (Default: False)
554 linked_places (bool): Add detailed information about the places
555 that link to the result. (Default: False)
556 parented_places (bool): Add detailed information about all places
557 for which the requested object is a parent, i.e. all places for
558 which the object provides the address details.
559 Only POI places can have parents. (Default: False)
560 keywords (bool): Add detailed information about the search terms
564 source_table (enum): Data source of the place. See below for possible values.
565 category (tuple): A tuple of two strings with the primary OSM tag
567 centroid (Point): Point position of the place.
568 place_id (Optional[int]): Internal ID of the place. This ID may differ
569 for the same place between different installations.
570 osm_object (Optional[tuple]): OSM type and ID of the place, if available.
571 names (Optional[dict]): Dictionary of names of the place. Keys are
572 usually the corresponding OSM tag keys.
573 address (Optional[dict]): Dictionary of address parts directly
574 attributed to the place. Keys are usually the corresponding
575 OSM tag keys with the `addr:` prefix removed.
576 extratags (Optional[dict]): Dictionary of additional attributes for
577 the place. Usually OSM tag keys and values.
578 housenumber (Optional[str]): House number of the place, normalised
579 for lookup. To get the house number in its original spelling,
580 use `address['housenumber']`.
581 postcode (Optional[str]): Computed postcode for the place. To get
582 directly attributed postcodes, use `address['postcode']` instead.
583 wikipedia (Optional[str]): Reference to a wikipedia site for the place.
584 The string has the format <language code>:<wikipedia title>.
585 rank_address (int): [Address rank](../customize/Ranking.md#address-rank).
586 rank_search (int): [Search rank](../customize/Ranking.md#search-rank).
587 importance (Optional[float]): Relative importance of the place. This is a measure
588 how likely the place will be searched for.
589 country_code (Optional[str]): Country the feature is in as
590 ISO 3166-1 alpha-2 country code.
591 address_rows (Optional[AddressLines]): List of places that make up the
592 computed address. `None` when `address_details` parameter was False.
593 linked_rows (Optional[AddressLines]): List of places that link to the object.
594 `None` when `linked_places` parameter was False.
595 parented_rows (Optional[AddressLines]): List of direct children of the place.
596 `None` when `parented_places` parameter was False.
597 name_keywords (Optional[WordInfos]): List of search words for the name of
598 the place. `None` when `keywords` parameter is set to False.
599 address_keywords (Optional[WordInfos]): List of search word for the address of
600 the place. `None` when `keywords` parameter is set to False.
601 bbox (Bbox): Bounding box of the full geometry of the place.
602 If the place is a single point, then the size of the bounding
603 box is guessed according to the type of place.
604 geometry (dict): Dictionary containing the full geometry of the place
605 in the formats requested in the `geometry_output` parameter.
606 distance (Optional[float]): Distance in degree from the input point.
608 return self._loop.run_until_complete(self._async_api.reverse(coord, **params))
611 def search(self, query: str, **params: Any) -> SearchResults:
612 """ Find a place by free-text search. Also known as forward geocoding.
615 query: Free-form text query searching for a place.
618 max_results (int): Maximum number of results to return. The
619 actual number of results may be less. (Default: 10)
620 min_rank (int): Lowest permissible rank for the result.
621 For addressable places this is the minimum
622 [address rank](../customize/Ranking.md#address-rank). For all
623 other places the [search rank](../customize/Ranking.md#search-rank)
625 max_rank (int): Highest permissible rank for the result. See min_rank above.
626 layers (enum): Defines the kind of data to take into account.
627 See [layers section](Input-Parameter-Types.md#layers) for details.
628 (Default: addresses and POIs)
629 countries (list[str]): Restrict search to countries with the given
630 ISO 3166-1 alpha-2 country code. An empty list (the default)
631 disables this filter.
632 excluded (list[int]): A list of internal IDs of places to exclude
634 viewbox (Optional[Bbox]): Bounding box of an area to focus search on.
635 bounded_viewbox (bool): Consider the bounding box given in `viewbox`
636 as a filter and return only results within the bounding box.
637 near (Optional[Point]): Focus search around the given point and
638 return results ordered by distance to the given point.
639 near_radius (Optional[float]): Restrict results to results within
640 the given distance in degrees of `near` point. Ignored, when
642 categories (list[tuple]): Restrict search to places of the given
643 categories. The category is the main OSM tag assigned to each
644 place. An empty list (the default) disables this filter.
645 geometry_output (enum): Add the full geometry of the place to the result.
646 Multiple formats may be selected. Note that geometries can become
647 quite large. (Default: none)
648 geometry_simplification (float): Simplification factor to use on
649 the geometries before returning them. The factor expresses
650 the tolerance in degrees from which the geometry may differ.
651 Topology is preserved. (Default: 0.0)
652 address_details (bool): Add detailed information about the places
653 that make up the address of the requested object. (Default: False)
654 linked_places (bool): Add detailed information about the places
655 that link to the result. (Default: False)
656 parented_places (bool): Add detailed information about all places
657 for which the requested object is a parent, i.e. all places for
658 which the object provides the address details.
659 Only POI places can have parents. (Default: False)
660 keywords (bool): Add detailed information about the search terms
664 source_table (enum): Data source of the place. See below for possible values.
665 category (tuple): A tuple of two strings with the primary OSM tag
667 centroid (Point): Point position of the place.
668 place_id (Optional[int]): Internal ID of the place. This ID may differ
669 for the same place between different installations.
670 osm_object (Optional[tuple]): OSM type and ID of the place, if available.
671 names (Optional[dict]): Dictionary of names of the place. Keys are
672 usually the corresponding OSM tag keys.
673 address (Optional[dict]): Dictionary of address parts directly
674 attributed to the place. Keys are usually the corresponding
675 OSM tag keys with the `addr:` prefix removed.
676 extratags (Optional[dict]): Dictionary of additional attributes for
677 the place. Usually OSM tag keys and values.
678 housenumber (Optional[str]): House number of the place, normalised
679 for lookup. To get the house number in its original spelling,
680 use `address['housenumber']`.
681 postcode (Optional[str]): Computed postcode for the place. To get
682 directly attributed postcodes, use `address['postcode']` instead.
683 wikipedia (Optional[str]): Reference to a wikipedia site for the place.
684 The string has the format <language code>:<wikipedia title>.
685 rank_address (int): [Address rank](../customize/Ranking.md#address-rank).
686 rank_search (int): [Search rank](../customize/Ranking.md#search-rank).
687 importance (Optional[float]): Relative importance of the place. This is a measure
688 how likely the place will be searched for.
689 country_code (Optional[str]): Country the feature is in as
690 ISO 3166-1 alpha-2 country code.
691 address_rows (Optional[AddressLines]): List of places that make up the
692 computed address. `None` when `address_details` parameter was False.
693 linked_rows (Optional[AddressLines]): List of places that link to the object.
694 `None` when `linked_places` parameter was False.
695 parented_rows (Optional[AddressLines]): List of direct children of the place.
696 `None` when `parented_places` parameter was False.
697 name_keywords (Optional[WordInfos]): List of search words for the name of
698 the place. `None` when `keywords` parameter is set to False.
699 address_keywords (Optional[WordInfos]): List of search word for the address of
700 the place. `None` when `keywords` parameter is set to False.
701 bbox (Bbox): Bounding box of the full geometry of the place.
702 If the place is a single point, then the size of the bounding
703 box is guessed according to the type of place.
704 geometry (dict): Dictionary containing the full geometry of the place
705 in the formats requested in the `geometry_output` parameter.
707 return self._loop.run_until_complete(
708 self._async_api.search(query, **params))
711 # pylint: disable=too-many-arguments
712 def search_address(self, amenity: Optional[str] = None,
713 street: Optional[str] = None,
714 city: Optional[str] = None,
715 county: Optional[str] = None,
716 state: Optional[str] = None,
717 country: Optional[str] = None,
718 postalcode: Optional[str] = None,
719 **params: Any) -> SearchResults:
720 """ Find an address using structured search.
723 amenity: Name of a POI.
724 street: Street and optionally housenumber of the address. If the address
725 does not have a street, then the place the housenumber references to.
726 city: Postal city of the address.
727 county: County equivalent of the address. Does not exist in all
729 state: State or province of the address.
730 country: Country with its full name or its ISO 3166-1 alpha-2 country code.
731 Do not use together with the country_code filter.
732 postalcode: Post code or ZIP for the place.
735 max_results (int): Maximum number of results to return. The
736 actual number of results may be less. (Default: 10)
737 min_rank (int): Lowest permissible rank for the result.
738 For addressable places this is the minimum
739 [address rank](../customize/Ranking.md#address-rank). For all
740 other places the [search rank](../customize/Ranking.md#search-rank)
742 max_rank (int): Highest permissible rank for the result. See min_rank above.
743 layers (enum): Defines the kind of data to take into account.
744 See [layers section](Input-Parameter-Types.md#layers) for details.
745 (Default: addresses and POIs)
746 countries (list[str]): Restrict search to countries with the given
747 ISO 3166-1 alpha-2 country code. An empty list (the default)
748 disables this filter. Do not use, when the country parameter
750 excluded (list[int]): A list of internal IDs of places to exclude
752 viewbox (Optional[Bbox]): Bounding box of an area to focus search on.
753 bounded_viewbox (bool): Consider the bounding box given in `viewbox`
754 as a filter and return only results within the bounding box.
755 near (Optional[Point]): Focus search around the given point and
756 return results ordered by distance to the given point.
757 near_radius (Optional[float]): Restrict results to results within
758 the given distance in degrees of `near` point. Ignored, when
760 categories (list[tuple]): Restrict search to places of the given
761 categories. The category is the main OSM tag assigned to each
762 place. An empty list (the default) disables this filter.
763 geometry_output (enum): Add the full geometry of the place to the result.
764 Multiple formats may be selected. Note that geometries can become
765 quite large. (Default: none)
766 geometry_simplification (float): Simplification factor to use on
767 the geometries before returning them. The factor expresses
768 the tolerance in degrees from which the geometry may differ.
769 Topology is preserved. (Default: 0.0)
770 address_details (bool): Add detailed information about the places
771 that make up the address of the requested object. (Default: False)
772 linked_places (bool): Add detailed information about the places
773 that link to the result. (Default: False)
774 parented_places (bool): Add detailed information about all places
775 for which the requested object is a parent, i.e. all places for
776 which the object provides the address details.
777 Only POI places can have parents. (Default: False)
778 keywords (bool): Add detailed information about the search terms
782 source_table (enum): Data source of the place. See below for possible values.
783 category (tuple): A tuple of two strings with the primary OSM tag
785 centroid (Point): Point position of the place.
786 place_id (Optional[int]): Internal ID of the place. This ID may differ
787 for the same place between different installations.
788 osm_object (Optional[tuple]): OSM type and ID of the place, if available.
789 names (Optional[dict]): Dictionary of names of the place. Keys are
790 usually the corresponding OSM tag keys.
791 address (Optional[dict]): Dictionary of address parts directly
792 attributed to the place. Keys are usually the corresponding
793 OSM tag keys with the `addr:` prefix removed.
794 extratags (Optional[dict]): Dictionary of additional attributes for
795 the place. Usually OSM tag keys and values.
796 housenumber (Optional[str]): House number of the place, normalised
797 for lookup. To get the house number in its original spelling,
798 use `address['housenumber']`.
799 postcode (Optional[str]): Computed postcode for the place. To get
800 directly attributed postcodes, use `address['postcode']` instead.
801 wikipedia (Optional[str]): Reference to a wikipedia site for the place.
802 The string has the format <language code>:<wikipedia title>.
803 rank_address (int): [Address rank](../customize/Ranking.md#address-rank).
804 rank_search (int): [Search rank](../customize/Ranking.md#search-rank).
805 importance (Optional[float]): Relative importance of the place. This is a measure
806 how likely the place will be searched for.
807 country_code (Optional[str]): Country the feature is in as
808 ISO 3166-1 alpha-2 country code.
809 address_rows (Optional[AddressLines]): List of places that make up the
810 computed address. `None` when `address_details` parameter was False.
811 linked_rows (Optional[AddressLines]): List of places that link to the object.
812 `None` when `linked_places` parameter was False.
813 parented_rows (Optional[AddressLines]): List of direct children of the place.
814 `None` when `parented_places` parameter was False.
815 name_keywords (Optional[WordInfos]): List of search words for the name of
816 the place. `None` when `keywords` parameter is set to False.
817 address_keywords (Optional[WordInfos]): List of search word for the address of
818 the place. `None` when `keywords` parameter is set to False.
819 bbox (Bbox): Bounding box of the full geometry of the place.
820 If the place is a single point, then the size of the bounding
821 box is guessed according to the type of place.
822 geometry (dict): Dictionary containing the full geometry of the place
823 in the formats requested in the `geometry_output` parameter.
825 return self._loop.run_until_complete(
826 self._async_api.search_address(amenity, street, city, county,
827 state, country, postalcode, **params))
830 def search_category(self, categories: List[Tuple[str, str]],
831 near_query: Optional[str] = None,
832 **params: Any) -> SearchResults:
833 """ Find an object of a certain category near another place.
835 The near place may either be given as an unstructured search
836 query in itself or as a geographic area through the
837 viewbox or near parameters.
840 categories: Restrict search to places of the given
841 categories. The category is the main OSM tag assigned to each
843 near_query: Optional free-text query to define the are to
847 max_results (int): Maximum number of results to return. The
848 actual number of results may be less. (Default: 10)
849 min_rank (int): Lowest permissible rank for the result.
850 For addressable places this is the minimum
851 [address rank](../customize/Ranking.md#address-rank). For all
852 other places the [search rank](../customize/Ranking.md#search-rank)
854 max_rank (int): Highest permissible rank for the result. See min_rank above.
855 layers (enum): Defines the kind of data to take into account.
856 See [layers section](Input-Parameter-Types.md#layers) for details.
857 (Default: addresses and POIs)
858 countries (list[str]): Restrict search to countries with the given
859 ISO 3166-1 alpha-2 country code. An empty list (the default)
860 disables this filter.
861 excluded (list[int]): A list of internal IDs of places to exclude
863 viewbox (Optional[Bbox]): Bounding box of an area to focus search on.
864 bounded_viewbox (bool): Consider the bounding box given in `viewbox`
865 as a filter and return only results within the bounding box.
866 near (Optional[Point]): Focus search around the given point and
867 return results ordered by distance to the given point.
868 near_radius (Optional[float]): Restrict results to results within
869 the given distance in degrees of `near` point. Ignored, when
871 geometry_output (enum): Add the full geometry of the place to the result.
872 Multiple formats may be selected. Note that geometries can become
873 quite large. (Default: none)
874 geometry_simplification (float): Simplification factor to use on
875 the geometries before returning them. The factor expresses
876 the tolerance in degrees from which the geometry may differ.
877 Topology is preserved. (Default: 0.0)
878 address_details (bool): Add detailed information about the places
879 that make up the address of the requested object. (Default: False)
880 linked_places (bool): Add detailed information about the places
881 that link to the result. (Default: False)
882 parented_places (bool): Add detailed information about all places
883 for which the requested object is a parent, i.e. all places for
884 which the object provides the address details.
885 Only POI places can have parents. (Default: False)
886 keywords (bool): Add detailed information about the search terms
890 source_table (enum): Data source of the place. See below for possible values.
891 category (tuple): A tuple of two strings with the primary OSM tag
893 centroid (Point): Point position of the place.
894 place_id (Optional[int]): Internal ID of the place. This ID may differ
895 for the same place between different installations.
896 osm_object (Optional[tuple]): OSM type and ID of the place, if available.
897 names (Optional[dict]): Dictionary of names of the place. Keys are
898 usually the corresponding OSM tag keys.
899 address (Optional[dict]): Dictionary of address parts directly
900 attributed to the place. Keys are usually the corresponding
901 OSM tag keys with the `addr:` prefix removed.
902 extratags (Optional[dict]): Dictionary of additional attributes for
903 the place. Usually OSM tag keys and values.
904 housenumber (Optional[str]): House number of the place, normalised
905 for lookup. To get the house number in its original spelling,
906 use `address['housenumber']`.
907 postcode (Optional[str]): Computed postcode for the place. To get
908 directly attributed postcodes, use `address['postcode']` instead.
909 wikipedia (Optional[str]): Reference to a wikipedia site for the place.
910 The string has the format <language code>:<wikipedia title>.
911 rank_address (int): [Address rank](../customize/Ranking.md#address-rank).
912 rank_search (int): [Search rank](../customize/Ranking.md#search-rank).
913 importance (Optional[float]): Relative importance of the place. This is a measure
914 how likely the place will be searched for.
915 country_code (Optional[str]): Country the feature is in as
916 ISO 3166-1 alpha-2 country code.
917 address_rows (Optional[AddressLines]): List of places that make up the
918 computed address. `None` when `address_details` parameter was False.
919 linked_rows (Optional[AddressLines]): List of places that link to the object.
920 `None` when `linked_places` parameter was False.
921 parented_rows (Optional[AddressLines]): List of direct children of the place.
922 `None` when `parented_places` parameter was False.
923 name_keywords (Optional[WordInfos]): List of search words for the name of
924 the place. `None` when `keywords` parameter is set to False.
925 address_keywords (Optional[WordInfos]): List of search word for the address of
926 the place. `None` when `keywords` parameter is set to False.
927 bbox (Bbox): Bounding box of the full geometry of the place.
928 If the place is a single point, then the size of the bounding
929 box is guessed according to the type of place.
930 geometry (dict): Dictionary containing the full geometry of the place
931 in the formats requested in the `geometry_output` parameter.
933 return self._loop.run_until_complete(
934 self._async_api.search_category(categories, near_query, **params))