### Forward Geocoding with SearchEngine (Two-Step) Source: https://context7.com/mapbox/mapbox-search-android/llms.txt Use this snippet for online forward geocoding, category search, and reverse geocoding. It demonstrates the two-step process of getting `SearchSuggestion` objects and then resolving them to full `SearchResult` details. Ensure `SearchEngine` is created with built-in data providers for history and favorites. ```kotlin val searchEngine = SearchEngine.createSearchEngineWithBuiltInDataProviders( apiType = ApiType.SEARCH_BOX, settings = SearchEngineSettings() ) val options = SearchOptions( proximity = Point.fromLngLat(-122.4194, 37.7749), countries = listOf(IsoCountryCode("US")), languages = listOf(IsoLanguageCode("en")), limit = 5 ) // Step 1: Get lightweight suggestions (no coordinates yet) searchEngine.search( query = "coffee shop", options = options, callback = object : SearchSuggestionsCallback { override fun onSuggestions(suggestions: List, responseInfo: ResponseInfo) { if (suggestions.isEmpty()) return // Step 2: Resolve first suggestion to full SearchResult with coordinates searchEngine.select( suggestion = suggestions.first(), callback = object : SearchSelectionCallback { override fun onResult( suggestion: SearchSuggestion, result: SearchResult, responseInfo: ResponseInfo ) { println("Name: ${result.name}") println("Coordinate: ${result.coordinate}") println("Address: ${result.fullAddress}") println("Categories: ${result.categories}") // Expected output: // Name: Blue Bottle Coffee // Coordinate: Point [longitude=-122.3999, latitude=37.7821] // Address: 315 Linden St, San Francisco, CA 94102, United States // Categories: [coffee, cafe] } override fun onResults( suggestion: SearchSuggestion, results: List, responseInfo: ResponseInfo ) { // Called when suggestion type is Category or Brand results.forEach { println("${it.name}: ${it.coordinate}") } } override fun onSuggestions( suggestions: List, responseInfo: ResponseInfo ) { // Called when suggestion type is Query — do another select() if needed } override fun onError(e: Exception) { println("Select error: $e") } } ) } override fun onError(e: Exception) { println("Search error: $e") } } ) ``` -------------------------------- ### SearchPlaceBottomSheetView.OnBottomSheetStateChangedListener Source: https://github.com/mapbox/mapbox-search-android/blob/main/MapboxSearch/ui/api/api-metalava.txt Listener for changes in the bottom sheet's state. This interface is called when the bottom sheet's state changes, for example, when it is opened, closed, dragged, or settles. ```APIDOC public static fun interface SearchPlaceBottomSheetView.OnBottomSheetStateChangedListener { method public void onStateChanged(@com.mapbox.search.ui.view.place.SearchPlaceBottomSheetView.BottomSheetState int newState, boolean fromUser); } ``` -------------------------------- ### Initialize and Use OfflineSearchEngine Source: https://context7.com/mapbox/mapbox-search-android/llms.txt Demonstrates how to set up TileStore, download tiles, create an OfflineSearchEngine, and perform offline searches and reverse geocoding. Ensure to register an EngineReadyCallback before initiating searches. ```kotlin val tilesetDescriptor = OfflineSearchEngine.createTilesetDescriptor( dataset = "mbx-gen", version = "" ) val tileStore = TileStore.create() tileStore.setOption(TileStoreOptions.MAPBOX_ACCESS_TOKEN, Value.valueOf(YOUR_MAPBOX_TOKEN)) val tileRegionLoadOptions = TileRegionLoadOptions.Builder() .descriptors(listOf(tilesetDescriptor)) .geometry(Point.fromLngLat(-122.4194, 37.7749)) .acceptExpired(true) .build() tileStore.loadTileRegion("san-francisco", tileRegionLoadOptions, { /* progress */ }) { /* completion */ } val offlineEngine = OfflineSearchEngine.create( OfflineSearchEngineSettings( tileStore = tileStore, locationProvider = locationProvider ) ) offlineEngine.addEngineReadyCallback(object : OfflineSearchEngine.EngineReadyCallback { override fun onEngineReady() { offlineEngine.search( query = "hospital", options = OfflineSearchOptions( proximity = Point.fromLngLat(-122.4194, 37.7749), limit = 5 ), callback = object : OfflineSearchCallback { override fun onResults(results: List, responseInfo: OfflineResponseInfo) { results.forEach { r -> println("${r.name}: ${r.coordinate}") } } override fun onError(e: Exception) { println("Offline search error: $e") } } ) offlineEngine.reverseGeocoding( options = OfflineReverseGeoOptions(center = Point.fromLngLat(-122.4194, 37.7749)), callback = object : OfflineSearchCallback { override fun onResults(results: List, responseInfo: OfflineResponseInfo) { println("Offline reverse result: ${results.firstOrNull()?.name}") } override fun onError(e: Exception) { println("Error: $e") } } ) } }) offlineEngine.addOnIndexChangeListener(object : OfflineSearchEngine.OnIndexChangeListener { override fun onIndexChange(event: OfflineIndexChangeEvent) { println("Index updated: ${event.type}") } override fun onError(event: OfflineIndexErrorEvent) { println("Index error: ${event.message}") } }) ``` -------------------------------- ### Initialize SearchResultsView and SearchEngineUiAdapter Source: https://context7.com/mapbox/mapbox-search-android/llms.txt Set up the SearchResultsView with configuration and initialize the SearchEngine and OfflineSearchEngine. The SearchEngineUiAdapter binds these components to manage the search lifecycle and UI updates. ```kotlin searchResultsView = findViewById(R.id.search_results_view).apply { initialize( SearchResultsView.Configuration( CommonSearchViewConfiguration(DistanceUnitType.IMPERIAL) ) ) } val searchEngine = SearchEngine.createSearchEngineWithBuiltInDataProviders( apiType = ApiType.SEARCH_BOX, settings = SearchEngineSettings() ) val offlineEngine = OfflineSearchEngine.create( OfflineSearchEngineSettings(locationProvider = locationProvider) ) searchEngineUiAdapter = SearchEngineUiAdapter( view = searchResultsView, searchEngine = searchEngine, offlineSearchEngine = offlineEngine // optional — enables offline fallback ) ``` -------------------------------- ### Generate Documentation Source: https://github.com/mapbox/mapbox-search-android/blob/main/README.md Run this script to generate the top-level public classes overview using Dokka. Generated docs will be in the MapboxSearch/build/generated-docs/ directory. ```bash ./scripts/generate_docs.sh ``` -------------------------------- ### Initialize and Use SearchPlaceBottomSheetView Source: https://context7.com/mapbox/mapbox-search-android/llms.txt Initialize the SearchPlaceBottomSheetView with a configuration and set up action listeners for close, navigate, share, and state changes. This view displays full details of a selected place. ```kotlin searchPlaceView = findViewById(R.id.search_place_view) searchPlaceView.initialize(CommonSearchViewConfiguration(DistanceUnitType.IMPERIAL)) // Action listeners searchPlaceView.addOnCloseClickListener { mapMarkersManager.clearMarkers() searchPlaceView.hide() } searchPlaceView.addOnNavigateClickListener {\n // Launch navigation intent val geoUri = Uri.parse("geo:${searchPlace.coordinate.latitude()},${searchPlace.coordinate.longitude()}") startActivity(Intent(Intent.ACTION_VIEW, geoUri)) } searchPlaceView.addOnShareClickListener { val shareText = "${searchPlace.name}\n${searchPlace.address?.formattedAddress()}" startActivity(Intent.createChooser( Intent(Intent.ACTION_SEND).apply { type = "text/plain" putExtra(Intent.EXTRA_TEXT, shareText) }, "Share place" )) } searchPlaceView.addOnBottomSheetStateChangedListener {\n println("Sheet state changed to: $state for ${place.name}") } // Open from any result type fun showPlace(searchResult: SearchResult, responseInfo: ResponseInfo) { searchPlaceView.open(SearchPlace.createFromSearchResult(searchResult, responseInfo)) // Optionally update distance when location is available locationProvider.userDistanceTo(this, searchResult.coordinate) { distanceMeters -> distanceMeters?.let { searchPlaceView.updateDistance(it) } } } // From history record fun showHistoryPlace(record: HistoryRecord) { searchPlaceView.open(SearchPlace.createFromIndexableRecord(record, distanceMeters = null)) } // Check state if (!searchPlaceView.isHidden()) { searchPlaceView.hide() } ``` -------------------------------- ### Discover.create() Source: https://github.com/mapbox/mapbox-search-android/blob/main/MapboxSearch/discover/api/api-metalava.txt Creates an instance of the Discover API. Overloads allow for providing a LocationProvider or using the default. ```APIDOC ## Discover.create() ### Description Creates an instance of the Discover API. This method can be called with or without a `LocationProvider`. ### Method `static Discover create(LocationProvider? locationProvider = defaultLocationProvider()) static Discover create() ``` -------------------------------- ### Manage Search History and Favorites with Local Data Providers Source: https://context7.com/mapbox/mapbox-search-android/llms.txt Demonstrates how to obtain, use, and manage search history and favorites using `HistoryDataProvider` and `FavoritesDataProvider`. Includes saving, retrieving, removing, and listening for changes to favorite records, as well as viewing search history. ```kotlin val historyProvider = ServiceProvider.INSTANCE.historyDataProvider() val favoritesProvider = ServiceProvider.INSTANCE.favoritesDataProvider() // Save a search result as a favorite val favorite = FavoriteRecord( id = searchResult.id, name = searchResult.name, descriptionText = searchResult.descriptionText, address = searchResult.address, routablePoints = searchResult.routablePoints, categories = searchResult.categories, makiIcon = searchResult.makiIcon, coordinate = searchResult.coordinate, metadata = searchResult.metadata, newType = searchResult.newTypes.firstOrNull() ?: NewSearchResultType.POI, timestamp = System.currentTimeMillis() ) favoritesProvider.upsert(favorite, object : CompletionCallback { override fun onComplete(result: Unit) { println("Saved to favorites") } override fun onError(e: Exception) { println("Error saving favorite: $e") } }) // Retrieve all favorites favoritesProvider.getAll(object : CompletionCallback> { override fun onComplete(result: List) { result.forEach { fav -> println("Favorite: ${fav.name} @ ${fav.coordinate}") } // Expected output: // Favorite: Blue Bottle Coffee @ Point [longitude=-122.3999, latitude=37.7821] // Favorite: San Francisco Airport @ Point [longitude=-122.3789, latitude=37.6213] } override fun onError(e: Exception) { println("Error fetching favorites: $e") } }) // Remove a specific favorite favoritesProvider.remove("record-id-123", object : CompletionCallback { override fun onComplete(result: Boolean) { println("Removed: $result") } override fun onError(e: Exception) { println("Error removing: $e") } }) // Listen for data changes (e.g., to refresh a favorites list UI) favoritesProvider.addOnDataChangedListener { newData -> println("Favorites updated, total: ${newData.size}") } // View history (auto-populated when using SearchEngineWithBuiltInDataProviders) historyProvider.getAll(object : CompletionCallback> { override fun onComplete(result: List) { result.sortedByDescending { it.timestamp }.take(5).forEach { h -> println("History: ${h.name} (${java.util.Date(h.timestamp)})") } } override fun onError(e: Exception) { println("History error: $e") } }) ``` -------------------------------- ### createSearchEngine Source: https://github.com/mapbox/mapbox-search-android/blob/main/MapboxSearch/search-sdk/api/api-metalava.txt Creates a new instance of the SearchEngine. Multiple overloads are available for different configurations and deprecation. ```APIDOC ## createSearchEngine ### Description Factory method to create a `SearchEngine` instance with specified settings. ### Method `static createSearchEngine(com.mapbox.search.SearchEngineSettings settings)` ### Parameters * **settings** (com.mapbox.search.SearchEngineSettings) - The settings for the search engine. ### Deprecated Method `static createSearchEngine(com.mapbox.search.SearchEngineSettings settings)` ### Method Overloads `static createSearchEngine(com.mapbox.search.ApiType apiType, com.mapbox.search.SearchEngineSettings settings)` `static createSearchEngineWithBuiltInDataProviders(com.mapbox.search.SearchEngineSettings settings)` `static createSearchEngineWithBuiltInDataProviders(com.mapbox.search.SearchEngineSettings settings, java.util.concurrent.Executor executor)` `static createSearchEngineWithBuiltInDataProviders(com.mapbox.search.SearchEngineSettings settings, java.util.concurrent.Executor executor, com.mapbox.search.common.CompletionCallback callback)` `static createSearchEngineWithBuiltInDataProviders(com.mapbox.search.ApiType apiType, com.mapbox.search.SearchEngineSettings settings)` `static createSearchEngineWithBuiltInDataProviders(com.mapbox.search.ApiType apiType, com.mapbox.search.SearchEngineSettings settings, java.util.concurrent.Executor executor)` `static createSearchEngineWithBuiltInDataProviders(com.mapbox.search.ApiType apiType, com.mapbox.search.SearchEngineSettings settings, java.util.concurrent.Executor executor, com.mapbox.search.common.CompletionCallback callback)` ``` -------------------------------- ### Perform Discover Searches - Kotlin Source: https://context7.com/mapbox/mapbox-search-android/llms.txt Demonstrates how to perform nearby, region-based, and route-based discover searches. Requires initializing the Discover service and using a CoroutineScope for asynchronous operations. Results are handled using `onValue` and `onError` callbacks. ```kotlin val discover = Discover.create() lifecycleScope.launch { val userLocation = Point.fromLngLat(-122.4194, 37.7749) // Search nearby val nearbyResult = discover.search( query = DiscoverQuery.Category.COFFEE_SHOP_CAFE, proximity = userLocation, options = DiscoverOptions(limit = 5, language = IsoLanguageCode("en")) ) nearbyResult.onValue { results -> results.forEach { r -> println("${r.name} | ${r.address.formattedAddress()} | categories: ${r.categories}") } }.onError { e -> println("Nearby error: $e") } // Search within a bounding box val regionResult = discover.search( query = DiscoverQuery.Category.GAS_STATION, region = BoundingBox.fromLngLats(-122.5, 37.7, -122.3, 37.85), proximity = userLocation ) regionResult.onValue { results -> println("Gas stations in region: ${results.size}") } // Search along a navigation route (at least 2 points required) val route = listOf( Point.fromLngLat(-122.4194, 37.7749), Point.fromLngLat(-121.8863, 37.3382) ) val routeResult = discover.search( query = DiscoverQuery.Category.RESTAURANT, route = route, deviation = RouteDeviationOptions(TimeDeviationOptions(maxDetour = 10.0, navigationProfile = NavigationProfile.DRIVING)), options = DiscoverOptions(limit = 10) ) routeResult.onValue { results -> println("Restaurants along route (≤10 min detour): ${results.size}") results.forEach { r -> println(" ${r.name}: ${r.coordinate}") } // Expected output: // Restaurants along route (≤10 min detour): 8 // In-N-Out Burger: Point [longitude=-121.944, latitude=37.512] // Five Guys: Point [longitude=-121.978, latitude=37.531] } } ``` -------------------------------- ### Run Unit Tests Source: https://github.com/mapbox/mapbox-search-android/blob/main/README.md Execute unit tests for the search-sdk, ui, and search-sdk-common modules using Gradle. These tests are written using Kotlin Test DSL. ```bash ./gradlew :search-sdk:testReleaseUnitTest ``` ```bash ./gradlew :ui:testReleaseUnitTest ``` ```bash ./gradlew :search-sdk-common:testReleaseUnitTest ``` -------------------------------- ### SearchPlaceBottomSheetView Constructors Source: https://github.com/mapbox/mapbox-search-android/blob/main/MapboxSearch/ui/api/api-metalava.txt Constructors for initializing the SearchPlaceBottomSheetView. ```APIDOC ## SearchPlaceBottomSheetView Constructors ### Description Constructors for creating instances of `SearchPlaceBottomSheetView`. ### Method Signatures ```java public final SearchPlaceBottomSheetView(android.content.Context outerContext, android.util.AttributeSet? attrs = null, int defStyleAttr = 0, int defStyleRes = 0) public final SearchPlaceBottomSheetView(android.content.Context outerContext, android.util.AttributeSet? attrs = null, int defStyleAttr = 0) public final SearchPlaceBottomSheetView(android.content.Context outerContext, android.util.AttributeSet? attrs = null) public final SearchPlaceBottomSheetView(android.content.Context outerContext) ``` ``` -------------------------------- ### OfflineSearchEngine.Companion.create Source: https://github.com/mapbox/mapbox-search-android/blob/main/MapboxSearch/offline/api/api-metalava.txt Creates an instance of OfflineSearchEngine with the specified settings. ```APIDOC ## OfflineSearchEngine.Companion.create ### Description Creates an instance of `OfflineSearchEngine` with the specified settings. ### Method Signature ```java method public com.mapbox.search.offline.OfflineSearchEngine create(com.mapbox.search.offline.OfflineSearchEngineSettings settings); ``` ### Parameters - **settings** (OfflineSearchEngineSettings) - Required - The settings for the offline search engine. ``` -------------------------------- ### DetailsApiSettings Source: https://github.com/mapbox/mapbox-search-android/blob/main/MapboxSearch/search-sdk/api/api-metalava.txt Settings for configuring the DetailsApi, including location provider, viewport provider, and base URL. ```APIDOC ## DetailsApiSettings ### Description Settings for configuring the DetailsApi, including location provider, viewport provider, and base URL. ### Constructors DetailsApiSettings() DetailsApiSettings(LocationProvider? locationProvider) DetailsApiSettings(LocationProvider? locationProvider, ViewportProvider? viewportProvider) DetailsApiSettings(LocationProvider? locationProvider, ViewportProvider? viewportProvider, String? baseUrl) ### Properties - **locationProvider** (LocationProvider?): The location provider to use. - **viewportProvider** (ViewportProvider?): The viewport provider to use. - **baseUrl** (String?): The base URL for API requests. ``` -------------------------------- ### FavoritesDataProvider Operations Source: https://context7.com/mapbox/mapbox-search-android/llms.txt Demonstrates how to obtain instances of FavoritesDataProvider, upsert, retrieve, and remove favorite records, and listen for data changes. ```APIDOC ## FavoritesDataProvider ### Description Provides CRUD operations and change listener support for user-saved favorite records. ### Obtain Instance ```kotlin val favoritesProvider = ServiceProvider.INSTANCE.favoritesDataProvider() ``` ### Upsert Favorite Saves or updates a favorite record. ```kotlin val favorite = FavoriteRecord( id = searchResult.id, name = searchResult.name, descriptionText = searchResult.descriptionText, address = searchResult.address, routablePoints = searchResult.routablePoints, categories = searchResult.categories, makiIcon = searchResult.makiIcon, coordinate = searchResult.coordinate, metadata = searchResult.metadata, newType = searchResult.newTypes.firstOrNull() ?: NewSearchResultType.POI, timestamp = System.currentTimeMillis() ) favoritesProvider.upsert(favorite, object : CompletionCallback { override fun onComplete(result: Unit) { println("Saved to favorites") } override fun onError(e: Exception) { println("Error saving favorite: $e") } }) ``` ### Get All Favorites Retrieves all saved favorite records. ```kotlin favoritesProvider.getAll(object : CompletionCallback> { override fun onComplete(result: List) { result.forEach { fav -> println("Favorite: ${fav.name} @ ${fav.coordinate}") } } override fun onError(e: Exception) { println("Error fetching favorites: $e") } }) ``` ### Remove Favorite Removes a specific favorite record by its ID. ```kotlin favoritesProvider.remove("record-id-123", object : CompletionCallback { override fun onComplete(result: Boolean) { println("Removed: $result") } override fun onError(e: Exception) { println("Error removing: $e") } }) ``` ### Add Data Changed Listener Registers a listener to be notified when the favorites data changes. ```kotlin favoritesProvider.addOnDataChangedListener { newData -> println("Favorites updated, total: ${newData.size}") } ``` ``` -------------------------------- ### SearchEngineSettings.Builder Source: https://github.com/mapbox/mapbox-search-android/blob/main/MapboxSearch/search-sdk/api/api-metalava.txt A builder class for constructing `SearchEngineSettings` objects. ```APIDOC ## SearchEngineSettings.Builder ### Description A builder class used to construct `SearchEngineSettings` instances programmatically. ### Constructor ```java public SearchEngineSettings.Builder() ``` ### Methods - **baseUrl**: Sets the base URL for general API requests. - **build**: Constructs and returns the `SearchEngineSettings` object. - **geocodingEndpointBaseUrl**: Sets the base URL for geocoding requests. - **locationProvider**: Sets the location provider. - **singleBoxSearchBaseUrl**: Sets the base URL for single box search requests. - **viewportProvider**: Sets the viewport provider. ``` -------------------------------- ### SearchPlaceBottomSheetView Initialization Source: https://github.com/mapbox/mapbox-search-android/blob/main/MapboxSearch/ui/api/api-metalava.txt Method for initializing the bottom sheet view with search configuration. ```APIDOC ## Initialization ### Description Initializes the `SearchPlaceBottomSheetView` with the provided search view configuration. ### Method Signature ```java public void initialize(com.mapbox.search.ui.view.CommonSearchViewConfiguration commonSearchViewConfiguration) ``` ``` -------------------------------- ### DetailsApi.create() Source: https://github.com/mapbox/mapbox-search-android/blob/main/MapboxSearch/search-sdk/api/api-metalava.txt Creates an instance of the DetailsApi. This method can be called with or without settings. ```APIDOC ## DetailsApi.create() ### Description Creates an instance of the DetailsApi. This method can be called with or without settings. ### Method static DetailsApi create() ### Method static DetailsApi create(DetailsApiSettings settings) ``` -------------------------------- ### AddressAutofill.create() Source: https://github.com/mapbox/mapbox-search-android/blob/main/MapboxSearch/autofill/api/api-metalava.txt Creates an instance of the AddressAutofill interface. You can optionally provide a LocationProvider for location-aware autofill. ```APIDOC ## AddressAutofill.create() ### Description Creates an instance of the AddressAutofill interface. This method can be called with or without a `LocationProvider`. ### Method `static AddressAutofill create(LocationProvider? locationProvider = defaultLocationProvider()) static AddressAutofill create() ``` -------------------------------- ### SearchEngine Creation Source: https://github.com/mapbox/mapbox-search-android/blob/main/MapboxSearch/search-sdk/api/api-metalava.txt Methods for creating a SearchEngine instance with built-in data providers. You can optionally provide an executor for background tasks. ```APIDOC ## createSearchEngineWithBuiltInDataProviders ### Description Creates a SearchEngine instance with built-in data providers. This method allows for custom executor configuration. ### Method Signature ```java public com.mapbox.search.SearchEngine createSearchEngineWithBuiltInDataProviders(com.mapbox.search.ApiType apiType, com.mapbox.search.SearchEngineSettings settings, java.util.concurrent.Executor executor = SearchSdkMainThreadWorker.mainExecutor) ``` ### Parameters - **apiType** (com.mapbox.search.ApiType) - The API type to use. - **settings** (com.mapbox.search.SearchEngineSettings) - Settings for the SearchEngine. - **executor** (java.util.concurrent.Executor, optional) - The executor to use for background tasks. Defaults to `SearchSdkMainThreadWorker.mainExecutor`. --- ## createSearchEngineWithBuiltInDataProviders ### Description Creates a SearchEngine instance with built-in data providers. This is a convenience method that uses the default executor. ### Method Signature ```java public com.mapbox.search.SearchEngine createSearchEngineWithBuiltInDataProviders(com.mapbox.search.ApiType apiType, com.mapbox.search.SearchEngineSettings settings) ``` ### Parameters - **apiType** (com.mapbox.search.ApiType) - The API type to use. - **settings** (com.mapbox.search.SearchEngineSettings) - Settings for the SearchEngine. ``` -------------------------------- ### Integrate Address Autofill with Search Results View Source: https://context7.com/mapbox/mapbox-search-android/llms.txt Connect AddressAutofill to a SearchResultsView to display suggestions and handle address selection. Requires initializing the view and setting up a listener for suggestion selection and display. ```kotlin val addressAutofill = AddressAutofill.create(locationProvider = locationProvider) searchResultsView.initialize( SearchResultsView.Configuration( commonConfiguration = CommonSearchViewConfiguration(DistanceUnitType.METRIC) ) ) val autofillAdapter = AddressAutofillUiAdapter( view = searchResultsView, addressAutofill = addressAutofill ) autofillAdapter.addSearchListener(object : AddressAutofillUiAdapter.SearchListener { override fun onSuggestionSelected(suggestion: AddressAutofillSuggestion) { // Resolve full address and populate form fields lifecycleScope.launch { val result = addressAutofill.select(suggestion) result.onValue { autofillResult -> val address = autofillResult.address streetField.setText("${address.houseNumber} ${address.street}") cityField.setText(address.place) stateField.setText(address.region) zipField.setText(address.postcode) countryField.setText(address.country) searchResultsView.isVisible = false } } } override fun onSuggestionsShown(suggestions: List) { searchResultsView.isVisible = suggestions.isNotEmpty() } override fun onError(e: Exception) { Log.e("Autofill", "Error: $e") } }) // Trigger search as the user types (minimum 2 characters required) queryEditText.addTextChangedListener { val query = Query.create(text.toString()) if (query != null) { lifecycleScope.launch { autofillAdapter.search(query) } searchResultsView.isVisible = true } else { searchResultsView.isVisible = false } } ``` -------------------------------- ### getSettings Source: https://github.com/mapbox/mapbox-search-android/blob/main/MapboxSearch/search-sdk/api/api-metalava.txt Retrieves the SearchEngineSettings used to configure this SearchEngine. ```APIDOC ## getSettings ### Description Retrieves the `SearchEngineSettings` that were used to initialize this `SearchEngine`. ### Method `getSettings()` ### Returns `com.mapbox.search.SearchEngineSettings` - The search engine settings. ``` -------------------------------- ### Run Detekt Locally Source: https://github.com/mapbox/mapbox-search-android/blob/main/README.md Execute the Detekt static code analysis tool locally. Ensure you are in the MapboxSearch directory. ```bash cd MapboxSearch ./gradlew :search-sdk:detekt ``` -------------------------------- ### HistoryDataProvider Operations Source: https://context7.com/mapbox/mapbox-search-android/llms.txt Demonstrates how to obtain an instance of HistoryDataProvider and retrieve search history records. ```APIDOC ## HistoryDataProvider ### Description Provides access to the persistent on-device store for search history records. ### Obtain Instance ```kotlin val historyProvider = ServiceProvider.INSTANCE.historyDataProvider() ``` ### Get All History Retrieves all search history records, typically sorted by timestamp. ```kotlin historyProvider.getAll(object : CompletionCallback> { override fun onComplete(result: List) { result.sortedByDescending { it.timestamp }.take(5).forEach { println("History: ${it.name} (${java.util.Date(it.timestamp)})") } } override fun onError(e: Exception) { println("History error: $e") } }) ``` ``` -------------------------------- ### RouteOptions Source: https://github.com/mapbox/mapbox-search-android/blob/main/MapboxSearch/search-sdk/api/api-metalava.txt Options for defining a route. ```APIDOC ## RouteOptions ### Description Represents options for defining a route, including the path and deviation. ### Constructor - `RouteOptions(List route, Deviation deviation)`: Creates a `RouteOptions` object. ### Methods - `getDeviation()`: Returns the deviation options for the route. - `getRoute()`: Returns the list of points defining the route. ### Properties - `deviation` (Deviation): Deviation options for the route. - `route` (List): The list of points defining the route. ``` -------------------------------- ### Implement SearchListener for SearchEngineUiAdapter Source: https://context7.com/mapbox/mapbox-search-android/llms.txt Handle various search events by implementing the SearchListener interface. This includes showing suggestions, selecting results, handling offline results, history clicks, populating queries, and error reporting. ```kotlin searchEngineUiAdapter.addSearchListener(object : SearchEngineUiAdapter.SearchListener { override fun onSuggestionsShown(suggestions: List, responseInfo: ResponseInfo) { // Suggestions list updated in the view automatically } override fun onSearchResultSelected(searchResult: SearchResult, responseInfo: ResponseInfo) { // User tapped a result — show on map, open detail view, etc. mapMarkersManager.showMarker(searchResult.coordinate) searchPlaceView.open(SearchPlace.createFromSearchResult(searchResult, responseInfo)) } override fun onOfflineSearchResultSelected(result: OfflineSearchResult, responseInfo: OfflineResponseInfo) { mapMarkersManager.showMarker(result.coordinate) searchPlaceView.open(SearchPlace.createFromOfflineSearchResult(result)) } override fun onHistoryItemClick(historyRecord: HistoryRecord) { searchPlaceView.open(SearchPlace.createFromIndexableRecord(historyRecord, distanceMeters = null)) } override fun onPopulateQueryClick(suggestion: SearchSuggestion, responseInfo: ResponseInfo) { searchView.setQuery(suggestion.name, true) } override fun onError(e: Exception) { Toast.makeText(this@MainActivity, "Error: $e", Toast.LENGTH_SHORT).show() } // Other required overrides: override fun onSearchResultsShown(suggestion: SearchSuggestion, results: List, responseInfo: ResponseInfo) {} override fun onOfflineSearchResultsShown(results: List, responseInfo: OfflineResponseInfo) {} override fun onSuggestionSelected(searchSuggestion: SearchSuggestion): Boolean = false override fun onFeedbackItemClick(responseInfo: ResponseInfo) {} }) ``` -------------------------------- ### DiscoverOptions Source: https://github.com/mapbox/mapbox-search-android/blob/main/MapboxSearch/discover/api/api-metalava.txt Options for configuring a discover query, such as limit and language. ```APIDOC ## DiscoverOptions ### Description Options for configuring a discover query. ### Constructor - `DiscoverOptions(int limit = 10, IsoLanguageCode language = defaultLocaleLanguage())` ### Properties - **language** (IsoLanguageCode) - The language for the search results. - **limit** (int) - The maximum number of results to return. ``` -------------------------------- ### Format Kotlin Code with ktlint Source: https://github.com/mapbox/mapbox-search-android/blob/main/README.md Apply ktlint formatting to Kotlin code. This command should be executed from the MapboxSearch directory. ```bash ./gradlew :search-sdk:ktlintFormat ``` -------------------------------- ### PlaceAutocompleteOptions Source: https://github.com/mapbox/mapbox-search-android/blob/main/MapboxSearch/place-autocomplete/api/api-metalava.txt Options for configuring Place Autocomplete requests. ```APIDOC ## PlaceAutocompleteOptions Class ### Description Configurable options for place autocomplete requests, such as limiting results, specifying countries, language, and navigation profiles. ### Constructors - `PlaceAutocompleteOptions(limit: Int = 10, countries: List? = null, language: IsoLanguageCode = defaultLocaleLanguage(), types: List? = null, navigationProfile: NavigationProfile? = null)` - `PlaceAutocompleteOptions(limit: Int = 10, countries: List? = null, language: IsoLanguageCode = defaultLocaleLanguage(), types: List? = null)` - `PlaceAutocompleteOptions(limit: Int = 10, countries: List? = null, language: IsoLanguageCode = defaultLocaleLanguage())` - `PlaceAutocompleteOptions(limit: Int = 10, countries: List? = null)` - `PlaceAutocompleteOptions(limit: Int = 10)` - `PlaceAutocompleteOptions()` ### Methods - `getCountries()`: Returns the list of countries to filter results by. - `getLanguage()`: Returns the language code for the results. - `getLimit()`: Returns the maximum number of results to return. - `getNavigationProfile()`: Returns the navigation profile to use for routing. ``` -------------------------------- ### AddressAutofill.suggestions() Source: https://github.com/mapbox/mapbox-search-android/blob/main/MapboxSearch/autofill/api/api-metalava.txt Retrieves a list of address suggestions based on a user's query. ```APIDOC ## AddressAutofill.suggestions() ### Description Retrieves a list of address suggestions based on a user's query. This method can be configured with `AddressAutofillOptions`. ### Method suspend Object? suggestions(Query query, AddressAutofillOptions options, kotlin.coroutines.Continuation>>) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (Expected) - **List** - A list of address autofill suggestions. #### Response Example None ``` -------------------------------- ### TilesetParameters.Builder Source: https://github.com/mapbox/mapbox-search-android/blob/main/MapboxSearch/offline/api/api-metalava.txt Methods for configuring TilesetParameters. ```APIDOC ## TilesetParameters.Builder ### Description Provides methods to configure the parameters for offline tilesets, such as language and worldview. ### Methods #### `language(IsoLanguageCode language)` Sets the language for the tileset. - **language** (IsoLanguageCode) - Required - The language code for the tileset. #### `worldview(IsoLanguageCode language, IsoCountryCode worldview)` Sets the language and worldview for the tileset. - **language** (IsoLanguageCode) - Required - The language code for the tileset. - **worldview** (IsoCountryCode) - Required - The country code for the worldview. ### Properties - **dataset** (String) - The dataset identifier for the tileset. - **version** (String) - The version of the tileset. ``` -------------------------------- ### SearchOptions Constructors Source: https://github.com/mapbox/mapbox-search-android/blob/main/MapboxSearch/search-sdk/api/api-metalava.txt This section details the various constructors available for the SearchOptions class, allowing for flexible configuration of search parameters. ```APIDOC ## SearchOptions Constructors ### Description Provides multiple constructors for `SearchOptions` to customize search behavior. ### Constructors - `public SearchOptions(Point? proximity = null, BoundingBox? boundingBox = null, List? countries = null, Boolean? fuzzyMatch = null, List? languages = defaultSearchOptionsLanguage(), Integer? limit = null, @Deprecated List? types = null, List? newTypes = null, Integer? requestDebounce = null, Point? origin = null, SearchNavigationOptions? navigationOptions = null, @Deprecated RouteOptions? routeOptions = null, Map? unsafeParameters = null, boolean ignoreIndexableRecords = false, Double? indexableRecordsDistanceThresholdMeters = null)` - `public SearchOptions(Point? proximity = null, BoundingBox? boundingBox = null, List? countries = null, Boolean? fuzzyMatch = null, List? languages = defaultSearchOptionsLanguage(), Integer? limit = null, @Deprecated List? types = null, List? newTypes = null, Integer? requestDebounce = null, Point? origin = null, SearchNavigationOptions? navigationOptions = null, @Deprecated RouteOptions? routeOptions = null, Map? unsafeParameters = null, boolean ignoreIndexableRecords = false)` - `public SearchOptions(Point? proximity = null, BoundingBox? boundingBox = null, List? countries = null, Boolean? fuzzyMatch = null, List? languages = defaultSearchOptionsLanguage(), Integer? limit = null, @Deprecated List? types = null, List? newTypes = null, Integer? requestDebounce = null, Point? origin = null, SearchNavigationOptions? navigationOptions = null, @Deprecated RouteOptions? routeOptions = null, Map? unsafeParameters = null)` - `public SearchOptions(Point? proximity = null, BoundingBox? boundingBox = null, List? countries = null, Boolean? fuzzyMatch = null, List? languages = defaultSearchOptionsLanguage(), Integer? limit = null, @Deprecated List? types = null, List? newTypes = null, Integer? requestDebounce = null, Point? origin = null, SearchNavigationOptions? navigationOptions = null, @Deprecated RouteOptions? routeOptions = null)` - `public SearchOptions(Point? proximity = null, BoundingBox? boundingBox = null, List? countries = null, Boolean? fuzzyMatch = null, List? languages = defaultSearchOptionsLanguage(), Integer? limit = null, @Deprecated List? types = null, List? newTypes = null, Integer? requestDebounce = null, Point? origin = null, SearchNavigationOptions? navigationOptions = null)` - `public SearchOptions(Point? proximity = null, BoundingBox? boundingBox = null, List? countries = null, Boolean? fuzzyMatch = null, List? languages = defaultSearchOptionsLanguage(), Integer? limit = null, @Deprecated List? types = null, List? newTypes = null, Integer? requestDebounce = null, Point? origin = null)` - `public SearchOptions(Point? proximity = null, BoundingBox? boundingBox = null, List? countries = null, Boolean? fuzzyMatch = null, List? languages = defaultSearchOptionsLanguage(), Integer? limit = null, @Deprecated List? types = null, List? newTypes = null, Integer? requestDebounce = null)` ### Parameters - **proximity** (Point?) - The geographic point to use for proximity searches. - **boundingBox** (BoundingBox?) - The bounding box to limit search results within. - **countries** (List?) - A list of ISO country codes to filter results by. - **fuzzyMatch** (Boolean?) - Enables or disables fuzzy matching for search queries. - **languages** (List?) - A list of ISO language codes to prioritize for results. Defaults to `defaultSearchOptionsLanguage()`. - **limit** (Integer?) - The maximum number of search results to return. - **types** (@Deprecated List?) - Deprecated. Use `newTypes` instead. - **newTypes** (List?) - A list of new types to filter search results by. - **requestDebounce** (Integer?) - The debounce interval in milliseconds for search requests. - **origin** (Point?) - The geographic point representing the origin for navigation-related searches. - **navigationOptions** (SearchNavigationOptions?) - Options for navigation-specific searches. - **routeOptions** (@Deprecated RouteOptions?) - Deprecated. Use `navigationOptions` instead. - **unsafeParameters** (Map?) - A map of unsafe parameters that can be passed to the search service. - **ignoreIndexableRecords** (boolean) - Whether to ignore indexable records. - **indexableRecordsDistanceThresholdMeters** (Double?) - The distance threshold in meters for indexable records. ``` -------------------------------- ### CategorySearchOptions Constructors Source: https://github.com/mapbox/mapbox-search-android/blob/main/MapboxSearch/search-sdk/api/api-metalava.txt Provides multiple constructors for CategorySearchOptions, allowing for flexible initialization with various optional parameters. ```APIDOC ## CategorySearchOptions Constructors ### Description These constructors allow you to create `CategorySearchOptions` objects with different combinations of parameters to customize your search. ### Constructors - `CategorySearchOptions(proximity: Point?, boundingBox: BoundingBox?, countries: List?, fuzzyMatch: Boolean?, languages: List?, limit: Integer?, requestDebounce: Integer?, origin: Point?, navigationProfile: NavigationProfile?)` - `CategorySearchOptions(proximity: Point?, boundingBox: BoundingBox?, countries: List?, fuzzyMatch: Boolean?, languages: List?, limit: Integer?, requestDebounce: Integer?, origin: Point?)` - `CategorySearchOptions(proximity: Point?, boundingBox: BoundingBox?, countries: List?, fuzzyMatch: Boolean?, languages: List?, limit: Integer?, requestDebounce: Integer?)` - `CategorySearchOptions(proximity: Point?, boundingBox: BoundingBox?, countries: List?, fuzzyMatch: Boolean?, languages: List?, limit: Integer?)` - `CategorySearchOptions(proximity: Point?, boundingBox: BoundingBox?, countries: List?, fuzzyMatch: Boolean?, languages: List?)` - `CategorySearchOptions(proximity: Point?, boundingBox: BoundingBox?, countries: List?, fuzzyMatch: Boolean?)` - `CategorySearchOptions(proximity: Point?, boundingBox: BoundingBox?, countries: List?)` - `CategorySearchOptions(proximity: Point?, boundingBox: BoundingBox?)` - `CategorySearchOptions(proximity: Point?)` - `CategorySearchOptions()` ### Parameters - **proximity** (Point?): The geographic point around which to search. - **boundingBox** (BoundingBox?): A bounding box to limit the search area. - **countries** (List?): A list of ISO country codes to filter results. - **fuzzyMatch** (Boolean?): Enables fuzzy matching for search queries. - **languages** (List?): A list of ISO language codes for search results. - **limit** (Integer?): The maximum number of results to return. - **requestDebounce** (Integer?): The debounce interval for search requests. - **origin** (Point?): The starting point for navigation-related searches. - **navigationProfile** (NavigationProfile?): The navigation profile to use for routing. ``` -------------------------------- ### SearchEngineUiAdapter.SearchListener Source: https://github.com/mapbox/mapbox-search-android/blob/main/MapboxSearch/ui/api/api-metalava.txt Interface for listening to search events from SearchEngineUiAdapter. ```APIDOC ## SearchEngineUiAdapter.SearchListener ### Description Callback interface for receiving updates from the SearchEngineUiAdapter. ### Methods - `onError(e: Exception)`: Called when an error occurs during the search. ``` -------------------------------- ### Run Instrumentation and UI Tests Source: https://github.com/mapbox/mapbox-search-android/blob/main/README.md Execute all Android instrumentation and UI tests. This command requires at least one emulator to be available via adb. ```bash ./gradlew connectedAndroidTest mergeAndroidReports --continue ``` -------------------------------- ### OfflineSearchEngineSettings Source: https://github.com/mapbox/mapbox-search-android/blob/main/MapboxSearch/offline/api/api-metalava.txt Configure settings for the offline search engine, such as TileStore and base URI for tiles. ```APIDOC ## OfflineSearchEngineSettings ### Description Allows configuration of the offline search engine. ### Constructors - `OfflineSearchEngineSettings()`: Creates settings with default values. - `OfflineSearchEngineSettings(TileStore tileStore)`: Creates settings with a specified TileStore. - `OfflineSearchEngineSettings(TileStore tileStore, URI tilesBaseUri)`: Creates settings with a specified TileStore and base URI. ### Methods - `toBuilder()`: Returns a builder to create a new instance of `OfflineSearchEngineSettings`. - `getTileStore()`: Returns the configured TileStore. - `getTilesBaseUri()`: Returns the base URI for tiles. - `getLocationProvider()`: Returns the configured location provider. ### Properties - `tileStore` (TileStore): The TileStore used for offline data. - `tilesBaseUri` (URI): The base URI for fetching offline tiles. - `locationProvider` (LocationProvider?): The location provider for proximity-based searches. ``` -------------------------------- ### SearchSuggestionType.Brand Constructor Source: https://github.com/mapbox/mapbox-search-android/blob/main/MapboxSearch/search-sdk/api/api-metalava.txt Constructor for creating a SearchSuggestionType.Brand object. ```APIDOC ## SearchSuggestionType.Brand Constructor ### Description Creates a new instance of `SearchSuggestionType.Brand`. ### Parameters - **brandName** (String) - The name of the brand. - **brandId** (String) - The ID of the brand. ``` -------------------------------- ### CategorySearchOptions Constructors Source: https://github.com/mapbox/mapbox-search-android/blob/main/MapboxSearch/search-sdk/api/api-metalava.txt Construct CategorySearchOptions with various configurations. ```APIDOC ## CategorySearchOptions ### Description Defines options for category-based searches, allowing customization of location, country, language, and more. ### Constructors - **CategorySearchOptions(Point? proximity, BoundingBox? boundingBox, List? countries, Boolean? fuzzyMatch, List? languages, Integer? limit, Integer? requestDebounce, Point? origin, NavigationProfile? navigationProfile, RouteOptions? routeOptions, Map? unsafeParameters, boolean ignoreIndexableRecords, Double? indexableRecordsDistanceThresholdMeters, Boolean? ensureResultsPerCategory, List? attributeSets)**: Full constructor with all available options. - **CategorySearchOptions(Point? proximity, BoundingBox? boundingBox, List? countries, Boolean? fuzzyMatch, List? languages, Integer? limit, Integer? requestDebounce, Point? origin, NavigationProfile? navigationProfile, RouteOptions? routeOptions, Map? unsafeParameters, boolean ignoreIndexableRecords, Double? indexableRecordsDistanceThresholdMeters, Boolean? ensureResultsPerCategory)**: Constructor excluding attributeSets. - **CategorySearchOptions(Point? proximity, BoundingBox? boundingBox, List? countries, Boolean? fuzzyMatch, List? languages, Integer? limit, Integer? requestDebounce, Point? origin, NavigationProfile? navigationProfile, RouteOptions? routeOptions, Map? unsafeParameters, boolean ignoreIndexableRecords, Double? indexableRecordsDistanceThresholdMeters)**: Constructor excluding ensureResultsPerCategory and attributeSets. - **CategorySearchOptions(Point? proximity, BoundingBox? boundingBox, List? countries, Boolean? fuzzyMatch, List? languages, Integer? limit, Integer? requestDebounce, Point? origin, NavigationProfile? navigationProfile, RouteOptions? routeOptions, Map? unsafeParameters, boolean ignoreIndexableRecords)**: Constructor excluding indexableRecordsDistanceThresholdMeters, ensureResultsPerCategory, and attributeSets. - **CategorySearchOptions(Point? proximity, BoundingBox? boundingBox, List? countries, Boolean? fuzzyMatch, List? languages, Integer? limit, Integer? requestDebounce, Point? origin, NavigationProfile? navigationProfile, RouteOptions? routeOptions, Map? unsafeParameters)**: Constructor excluding ignoreIndexableRecords and subsequent options. - **CategorySearchOptions(Point? proximity, BoundingBox? boundingBox, List? countries, Boolean? fuzzyMatch, List? languages, Integer? limit, Integer? requestDebounce, Point? origin, NavigationProfile? navigationProfile, RouteOptions? routeOptions)**: Constructor excluding unsafeParameters and subsequent options. ``` -------------------------------- ### SearchEngineUiAdapter Source: https://github.com/mapbox/mapbox-search-android/blob/main/MapboxSearch/ui/api/api-metalava.txt Adapts the SearchEngine for UI integration, providing methods to add/remove listeners, perform searches, and manage search mode. ```APIDOC ## SearchEngineUiAdapter ### Description Provides UI adaptation for the core search engine. It allows for managing search listeners, performing searches, selecting features, and controlling the search mode. ### Methods - `addSearchListener(listener: SearchEngineUiAdapter.SearchListener)`: Adds a listener to receive search events. - `removeSearchListener(listener: SearchEngineUiAdapter.SearchListener)`: Removes a previously added search listener. - `search(query: String, options: SearchOptions)`: Performs a search with specified options. - `search(query: String)`: Performs a basic search with a query string. - `select(feature: Feature)`: Selects a specific feature for display or interaction. - `setSearchMode(searchMode: SearchMode)`: Sets the current search mode. - `getSearchMode()`: Returns the current search mode. ```