Installation
To use the Search SDK, you'll need to configure your credentials and add the SDK as a dependency.
Configure credentials
Before installing the SDK, you will need to gather the appropriate credentials. The SDK requires two pieces of sensitive information from your Mapbox account. If you don't have a Mapbox account: sign up and navigate to your Account page. You'll need:
- A public access token: From your account's tokens page, you can either copy your default public token or click the Create a token button to create a new public token.
- A secret access token with the
Downloads:Read
scope.- From your account's tokens page, click the Create a token button.
- From the token creation page, give your token a name and make sure the box next to the
Downloads:Read
scope is checked. - Click the Create token button at the bottom of the page to create your token.
- The token you've created is a secret token, which means you will only have one opportunity to copy it somewhere secure.
You should not expose these access tokens in publicly-accessible source code where unauthorized users might find them. Instead, you should store them somewhere safe on your computer and take advantage of Gradle properties to make sure they're only added when your app is compiled. Once this configuration step has been completed, you will be able to reference your credentials in other parts of your app.
Configure your secret token
To avoid exposing your secret token, add it as an environment variable:
- Find or create a
gradle.properties
file in your Gradle user home folder. The folder can be found at«USER_HOME»/.gradle
. Once you have found or created the file, its path should be«USER_HOME»/.gradle/gradle.properties
. You can read more about Gradle properties in the official Gradle documentation. - Add your secret token your
gradle.properties
file:
MAPBOX_DOWNLOADS_TOKEN=YOUR_SECRET_MAPBOX_ACCESS_TOKEN
Configure your public token
There are many ways to configure your public access token. Many of the examples and code snippets on this site assume your token is stored in a file in your project with other string values. If you would like to manage your public access token this way, open your project's R.strings.xml
file and add the following string resource, replacing YOUR_MAPBOX_ACCESS_TOKEN
with your public Mapbox API token:
<string name="mapbox_access_token">YOUR_MAPBOX_ACCESS_TOKEN</string>
If you ever need to rotate your access token, you will need to update the token value in your R.strings.xml
file.
Configure permissions
You can use the Manifest merge feature to reduce the need to include any SDK requirements in your application's manifest file. You'll need to add either the Fine or Coarse location permission if you plan to display a user's location on the map or get the user's location information. The user location permission should also be checked during runtime using the PermissionsManager
.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Learn how to keep access tokens private in mobile apps.
Add the dependency
Mapbox provides the Search SDK via Maven.
To add the Search SDK as a dependency, you will need to configure your build to download the Search SDK from Mapbox directly. This requires a valid username and password.
-
Open your project in Android Studio.
-
Open up your module-level
build.gradle
file. -
The Search SDK uses Java 8 features. To enable Java 8 in your project, add the following compileOptions:
android { ... // Configure only for each module that uses Java 8 // language features (either in its source code or // through dependencies). compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } // For Kotlin projects kotlinOptions { jvmTarget = "1.8" } }
-
Make sure that your project's
minSdkVersion
is at API 21 or higher.android { ... defaultConfig { minSdkVersion 21 } }
-
Add the dependency under
dependencies
. There are two options:-
Option 1: To use the Search SDK with pre-built UI components, add the Search UI SDK (
mapbox-search-android-ui
) dependency. This will also include Search Core (mapbox-search-android
) automatically.dependencies { implementation "com.mapbox.search:mapbox-search-android-ui:1.0.0-beta.34" }
-
Option 2: To use the Search SDK without pre-built UI components, add the Search Core (
mapbox-search-android
) dependency.dependencies { implementation "com.mapbox.search:mapbox-search-android:1.0.0-beta.34" }
-
-
Open up your project-level
build.gradle
file. Declare the Mapbox Downloads API'sv2/releases/maven
endpoint in therepositories
block. To download the Search SDK, you must authenticate your request with a valid username and password. In the previous section, you added your secret token as a password in the gradle.properties file in your Gradle user home folder.allprojects { repositories { maven { url 'https://api.mapbox.com/downloads/v2/releases/maven' authentication { basic(BasicAuthentication) } credentials { // Do not change the username below. // This should always be `mapbox` (not your username). username = "mapbox" // Use the secret token you stored in gradle.properties as the password password = project.properties['MAPBOX_DOWNLOADS_TOKEN'] ?: "" } } } }
-
Because you've edited your Gradle files, Android Studio will ask you whether you want to sync the Gradle files. You can sync now.
Add search to an app
Open the activity’s XML manifest file. Set permissions and reference the name of the Application you created in the last step:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /><uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <applicationandroid:allowBackup="true"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"android:roundIcon="@mipmap/ic_launcher_round"android:theme="@style/AppTheme"> <activityandroid:name=".MainActivity"android:exported="true"> <intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity></application>
Open the activity’s XML layout file and add the following view:
<?xml version="1.0" encoding="utf-8"?><FrameLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"> <EditTextandroid:id="@+id/query_edit_text"android:layout_width="match_parent"android:layout_height="56dp"android:hint="Where to?"android:paddingHorizontal="16dp"/> <com.mapbox.search.ui.view.SearchResultsViewandroid:id="@+id/search_results_view"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_marginTop="56dp"android:paddingVertical="16dp"/></FrameLayout>
Create a new Activity or open an existing Activity and add the code below:
import android.Manifest.permissionimport android.content.Contextimport android.content.pm.PackageManagerimport android.os.Bundleimport android.text.Editableimport android.text.TextWatcherimport android.widget.EditTextimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivityimport androidx.core.app.ActivityCompatimport androidx.core.content.ContextCompatimport com.mapbox.search.OfflineSearchEngineSettingsimport com.mapbox.search.ResponseInfoimport com.mapbox.search.SearchEngineSettingsimport com.mapbox.search.record.HistoryRecordimport com.mapbox.search.result.SearchResultimport com.mapbox.search.result.SearchSuggestionimport com.mapbox.search.ui.view.CommonSearchViewConfigurationimport com.mapbox.search.ui.view.DistanceUnitTypeimport com.mapbox.search.ui.view.SearchResultsView class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_main) val queryEditText = findViewById<EditText>(R.id.query_edit_text) val searchResultsView = findViewById<SearchResultsView>(R.id.search_results_view)val accessToken = getString(R.string.mapbox_access_token)searchResultsView.initialize(SearchResultsView.Configuration(commonConfiguration = CommonSearchViewConfiguration(DistanceUnitType.IMPERIAL),searchEngineSettings = SearchEngineSettings(accessToken),offlineSearchEngineSettings = OfflineSearchEngineSettings(accessToken))) searchResultsView.addSearchListener(object : SearchResultsView.SearchListener { private fun showToast(message: String) {Toast.makeText(applicationContext, message, Toast.LENGTH_SHORT).show()} override fun onHistoryItemClicked(historyRecord: HistoryRecord) {showToast("HistoryRecord clicked: ${historyRecord.name}")} override fun onSearchResult(searchResult: SearchResult, responseInfo: ResponseInfo) {showToast("SearchResult clicked: ${searchResult.name}")} override fun onPopulateQueryClicked(suggestion: SearchSuggestion,responseInfo: ResponseInfo) {queryEditText.setText(suggestion.name)} override fun onCategoryResult(suggestion: SearchSuggestion,results: List<SearchResult>,responseInfo: ResponseInfo) {// not implemented} override fun onError(e: Exception) {// not implemented} override fun onFeedbackClicked(responseInfo: ResponseInfo) {// not implemented} override fun onOfflineSearchResults(results: List<SearchResult>, responseInfo: ResponseInfo) {// not implemented} override fun onSuggestions(suggestions: List<SearchSuggestion>, responseInfo: ResponseInfo) {// not implemented}}) queryEditText.addTextChangedListener(object : TextWatcher { override fun onTextChanged(s: CharSequence, start: Int, before: Int, after: Int) {searchResultsView.search(s.toString())} override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {// not implemented} override fun afterTextChanged(e: Editable) { /* not implemented */ }}) if (!isPermissionGranted(permission.ACCESS_FINE_LOCATION)) {ActivityCompat.requestPermissions(this,arrayOf(permission.ACCESS_FINE_LOCATION, permission.ACCESS_COARSE_LOCATION),PERMISSIONS_REQUEST_LOCATION)}} private companion object { private const val PERMISSIONS_REQUEST_LOCATION = 0 fun Context.isPermissionGranted(permission: String): Boolean {return ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED}}}
Run your application and you will see a functional search UI. Begin typing in the search bar to see results: