Skip to main content

Getting started with Search

|

The Maps SDK for Android provides a flexible and robust search functionality, allowing the search of locations using text queries and coordinates:

  • Text Search: Perform searches using a text query and geographic coordinates to prioritize results within a specific area.
  • Search Preferences: Customize search behavior using various options, such as allowing fuzzy results, limiting search distance, or specifying the number of results.
  • Category-Based Search: Filter search results by predefined categories, such as gas stations or parking areas.
  • Proximity Search: Retrieve all nearby landmarks without specifying a text query.

The simplest way to search for something is by providing text and specifying coordinates. The coordinates serve as a hint, prioritizing points of interest (POIs) within the indicated area.

val textFilter = "Paris"
val reference = Coordinates(45.0, 10.0)
val preferences = SearchPreferences().apply {
maxMatches = 40
allowFuzzyResults = true
}

val searchService = SearchService(
preferences = preferences,
onCompleted = { results, errorCode, hint ->
// If there is an error or there aren't any results, the method will return an empty list.
when (errorCode) {
GemError.NoError -> {
if (results.isEmpty()) {
Log.d("SearchService", "No results")
} else {
Log.d("SearchService", "Number of results: ${results.size}")
}
}
else -> {
Log.e("SearchService", "Error: ${GemError.getMessage(errorCode)}")
}
}
}
)

val result = searchService.searchByFilter(textFilter, reference)
info

The searchByFilter method returns an error code. If the search fails to initialize, the error details will be delivered through the onCompleted callback function.

The errorCode provided by the callback function can have the following values:

ValueSignificance
GemError.NoErrorsuccessfully completed
GemError.Cancelcancelled by the user
GemError.NoMemorysearch engine couldn't allocate the necessary memory for the operation
GemError.OperationTimeoutsearch was executed on the online service and the operation took too much time to complete (usually more than 1 min, depending on the server overload state)
GemError.NetworkTimeoutcan't establish the connection or the server didn't respond on time
GemError.NetworkFailedsearch was executed on the online service and the operation failed due to bad network connection

Specifying preferences

As seen in the previous example, before searching we need to specify some SearchPreferences. The following characteristics apply to a search:

FieldTypeDefault ValueExplanation
allowFuzzyResultsBooleantrueAllows fuzzy search results, enabling approximate matches for queries.
exactMatchEnabledBooleanfalseRestricts results to only those that exactly match the query.
maxMatchesInt40Specifies the maximum number of search results to return.
searchAddressesEnabledBooleantrueIncludes addresses in the search results. This option also includes roads.
searchMapPOIsEnabledBooleantrueIncludes points of interest (POIs) on the map in the search results.
searchOnlyOnboardBooleanfalseLimits the search to onboard (offline) data only.
thresholdDistanceInt2147483647Defines the maximum distance (in meters) for search results from the query location.

Search by category

The Maps SDK for Android allows the user to filter results based on the category. Some predefined categories are available and can be accessed using EGenericCategoriesIDs.

In the following example, we perform a search for a text query, limiting the results to gas stations:

val textFilter = "Paris"
val reference = Coordinates(45.0, 10.0)
val preferences = SearchPreferences().apply {
maxMatches = 40
allowFuzzyResults = true
searchMapPOIsEnabled = true
searchAddressesEnabled = false
}

val searchService = SearchService(
preferences = preferences,
onCompleted = { results, errorCode, hint ->
when (errorCode) {
GemError.NoError -> {
if (results.isEmpty()) {
Log.d("SearchService", "No results")
} else {
Log.d("SearchService", "Number of results: ${results.size}")
}
}
else -> {
Log.e("SearchService", "Error: ${GemError.getMessage(errorCode)}")
}
}
}
)

val result = searchService.searchByFilter(
textFilter,
reference,
arrayListOf(EGenericCategoriesIDs.GasStation)
)
Tip

Set the searchAddressesEnabled to false in order to filter non-relevant results.

Search on custom landmarks

By default all search methods operate on the landmarks provided by default on the map. You can enable search functionality for custom landmarks by creating a landmark store containing the desired landmarks and adding it to the search preferences.

// Create the landmarks to be added
val landmark1 = Landmark("My Custom Landmark1", Coordinates(25.0, 30.0))
val landmark2 = Landmark("My Custom Landmark2", Coordinates(25.005, 30.005))

// Create a store and add the landmarks
val store = LandmarkStoreService.createLandmarkStore("LandmarksToBeSearched")
store.addLandmark(landmark1)
store.addLandmark(landmark2)

// Add the store to the search preferences
val preferences = SearchPreferences().apply {
landmarkStores?.add(store)
// If no results from the map POIs should be returned then searchMapPOIsEnabled should be set to false
searchMapPOIsEnabled = false
// If no results from the addresses should be returned then searchAddressesEnabled should be set to false
searchAddressesEnabled = false
}

val searchService = SearchService(
preferences = preferences,
onCompleted = { results, errorCode, hint ->
when (errorCode) {
GemError.NoError -> {
if (results.isEmpty()) {
Log.d("SearchService", "No results")
} else {
Log.d("SearchService", "Number of results: ${results.size}")
}
}
else -> {
Log.e("SearchService", "Error: ${GemError.getMessage(errorCode)}")
}
}
}
)

val result = searchService.searchByFilter(
"My Custom Landmark",
Coordinates(25.003, 30.003)
)
danger

The landmark store retains the landmarks added to it across sessions, until the app is uninstalled. This means a previously created landmark store with the same name might already exist in persistent storage and may contain pre-existing landmarks. For more details, refer to the documentation on LandmarkStore.

Tip

Set the searchAddressesEnabled and searchMapPOIsEnabled to false in order to filter non-relevant results.

Search on overlays

You can perform searches on overlays by specifying the overlay ID. It is recommended to consult the Overlay documentation for a deeper understanding and details about proper usage.

In the example below, we demonstrate how to search within items from the safety overlay. Custom overlays can also be used, provided they are activated in the applied map style:

// Get the overlay id of safety
val overlayId = ECommonOverlayIds.Safety.value

// Add the overlay to the search preferences
val preferences = SearchPreferences().apply {
// We can set searchMapPOIsEnabled and searchAddressesEnabled to false if no results from the map POIs and addresses should be returned
searchMapPOIsEnabled = false
searchAddressesEnabled = false
}

val searchService = SearchService(
preferences = preferences,
onCompleted = { results, errorCode, hint ->
when (errorCode) {
GemError.NoError -> {
if (results.isEmpty()) {
Log.d("SearchService", "No results")
} else {
val mapView: MapView? = findViewById<GemSurfaceView>(R.id.gem_surface).mapview
mapView?.centerOnCoordinates(results.first().coordinates)
Log.d("SearchService", "Number of results: ${results.size}")
}
}
else -> {
Log.e("SearchService", "Error: ${GemError.getMessage(errorCode)}")
}
}
}
)

val result = searchService.searchByFilter(
"Speed",
Coordinates(48.76930, 2.34483)
)

In order to convert the returned Landmark to a OverlayItem use the overlayItem property of the Landmark class. This property returns the associated OverlayItem if available, null otherwise.

Tip

Set the searchAddressesEnabled and searchMapPOIsEnabled to false in order to filter non-relevant results.

Search for location

If you don't specify any text, all the landmarks in the closest proximity are returned, limited to maxMatches.

val reference = Coordinates(45.0, 10.0)
val preferences = SearchPreferences().apply {
maxMatches = 40
allowFuzzyResults = true
}

val searchService = SearchService(
preferences = preferences,
onCompleted = { results, errorCode, hint ->
// If there is an error or there aren't any results, the method will return an empty list.
when (errorCode) {
GemError.NoError -> {
if (results.isEmpty()) {
Log.d("SearchService", "No results")
} else {
Log.d("SearchService", "Number of results: ${results.size}")
}
}
else -> {
Log.e("SearchService", "Error: ${GemError.getMessage(errorCode)}")
}
}
}
)

val result = searchService.searchAroundPosition(reference)

To limit the search to a specific area, provide a RectangleGeographicArea to the optional locationHint parameter.

val reference = Coordinates(41.68905, -72.64296)
val searchArea = RectangleGeographicArea(
Coordinates(41.98846, -73.12412), // topLeft
Coordinates(41.37716, -72.02342) // bottomRight
)

val searchService = SearchService(
preferences = SearchPreferences().apply { maxMatches = 400 },
locationHint = searchArea,
onCompleted = { results, errorCode, hint ->
// Handle results
}
)

val result = searchService.searchByFilter("N", reference)
danger

The reference coordinates used for search must be located within the RectangleGeographicArea provided to the locationHint parameter. Otherwise, the search will return an empty list.

Show the results on the map

In most use cases the landmarks found by search are already present on the map. If the search was made on custom landmark stores see the add map landmarks section for adding landmarks to the map.

To zoom to a landmark found via search, we can use MapView.centerOnCoordinates() on the coordinates of the landmark found (Landmark.coordinates). See the documentation for map centering for more info.

Change the language of the results

The language of search results and category names is determined by the SdkSettings.language setting. Check the the internationalization guide section for more details.