メインコンテンツまでスキップ

Get Started with the Search SDK for Android

This guide describes the steps to install the latest version of the Mapbox Search SDK for Android, configure your Android app to use the SDK, and do a search using the place-autocomplete module.

Prerequisites

  • A Mapbox account: Sign up or log into a free account on Mapbox.
  • Android Studio: This guide includes details specific to the latest version of Android Studio.

Part 1: Configure your credentials

Step 1: Create a secret token

A secret access token is required to download the SDK dependencies in your Android project. This token is used by gradle to authenticate with the Mapbox maven server where the SDK packages are hosted.

To create a secret token, follow these steps:

  1. Go to your account's tokens page.
  2. Click the Create a token button.
  3. Name your token, for this example we've used InstallTokenAndroid.
  4. Scroll down to the Secret Scope section and check the Downloads:Read scope box.
  5. Click the Create token button at the bottom of the page to create your token.
  6. Enter your password to confirm the creation of your token.
  7. Now, you'll be returned to your account's tokens page, where you can copy your created token. Note, this token is a secret token, which means you will only have one opportunity to copy it, so save this token somewhere secure.
Protect secret access tokens

You should not expose secret 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.

Step 2: Configure your secret token

Next, add your secret token to your global gradle.properties file. The global gradle.properties file is located in your Gradle user home folder.

If you don't have a gradle.properties file, create one. Add your secret token to the gradle.properties file as shown below, replacing the placeholder YOUR_SECRET_MAPBOX_ACCESS_TOKEN with your secret token.

~/.gradle/gradle.properties
MAPBOX_DOWNLOADS_TOKEN=YOUR_SECRET_MAPBOX_ACCESS_TOKEN

Step 3: Configure your public token

Your app must have a public access token configured to associate its usage of Mapbox resources with your account. Add a public access token from your Mapbox account as an Android string resource.

To do this, follow these steps:

  1. Open your project folder or create a new project in Android Studio.
  • If creating a new project, we recommend using the Empty Activity project type.
  1. Go to the folder structure in the left side of Android Studio and open your resource folder located at app/res/values.
  2. Create a new resource file, by left clicking on the folder, selecting New > Values Resource File
  3. Name the file mapbox_access_token.xml and click the Ok button.
  4. In the new file, copy and paste the code snippet below. If you are signed in, this snippet will already contain your default public token (a long string that starts with pk.). If you are not signed in, you will need to replace the placeholder YOUR_MAPBOX_ACCESS_TOKEN with a token from your account's tokens page.
app/res/values/mapbox_access_token.xml
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:tools="http://schemas.android.com/tools">
<string name="mapbox_access_token" translatable="false" tools:ignore="UnusedResources">YOUR_MAPBOX_ACCESS_TOKEN</string>
</resources>

Your public access token is now available for use in your Android project. You will access it via the string resource you created in your implementation code.

Advanced Topics: Best Practices, Rotating Tokens & Adding Tokens at Runtime
GUIDE
Access token best practices

Learn how to keep access tokens private in mobile apps.

Adding Tokens at Runtime

You can also implement tokens at runtime, but this requires you to have a separate server to store your tokens. This is helpful if you want to rotate your tokens or add additional security by storing your tokens outside of the APK, but is a much more complex method of implementation.

If you do choose to follow this method, we recommend calling MapboxOptions.accessToken = YOUR_PUBLIC_MAPBOX_ACCESS_TOKEN before inflating the MapView, otherwise the app will crash.

Rotating Tokens

For more information on access token rotation, consult the Access Tokens Information page.

Part 2: Add the dependencies

With your access tokens configured, you're ready to add the Search SDK as a dependency to your project.

Step 1: Add the Mapbox Maven repository

Mapbox provides the Maps SDK dependencies via a private Maven repository. To download dependencies, you must add the Maven repository's URL to your project.

  1. In Android Studio, under Gradle Scripts, open the settings.gradle file.
  2. Add a new maven {...} definition inside dependencyResolutionManagement.repositories.
settings.gradle
 
// Mapbox Maven repository
 
maven {
 
url = uri("https://api.mapbox.com/downloads/v2/releases/maven")
 
authentication {

Step 2: Add Search SDK dependencies

Next, add Search SDK modules to your project.

  1. In Android Studio, open your module-level build.gradle file.

  2. Make sure that your project's minSdk is 21 or higher:

build.gradle
android {
...
defaultConfig {
minSdk 21
...
}
}
  1. Add the Search SDK dependencies under dependencies. You can add one or more of the following modules, depending on which Search SDK functionality you need.
ModuleDescription
com.mapbox.search:place-autocompleteEnables Search by Text, providing results as the user types, and Search by Coordinate, providing results near a location.
com.mapbox.search:discoverEnables Search by Category, providing restaurants, businesses, and other points of interest near a given point or area.
com.mapbox.search:autofillEnables Address Autofill, filling of address form text inputs via interactive location search.
com.mapbox.search:mapbox-search-android-uiProvides ready-to-use UI components such as a search results list and a card for presenting details about a search result.
com.mapbox.search:mapbox-search-androidProvides advanced functionality including the SearchEngine class, custom data providers, search history,
com.mapbox.search:offlineSupports offline search capabilities.
build.gradle
dependencies {
...
implementation "com.mapbox.search:autofill:2.7.0"
implementation "com.mapbox.search:discover:2.7.0"
implementation "com.mapbox.search:place-autocomplete:2.7.0"
implementation "com.mapbox.search:offline:2.7.0"
implementation "com.mapbox.search:mapbox-search-android:2.7.0"
implementation "com.mapbox.search:mapbox-search-android-ui:2.7.0"
...
}

Part 3: Integrate the Search SDK

Try a Place Autocomplete Search without UI

To confirm that the Search SDK dependencies are correctly installed and your tokens are configured properly, add code to do a search using the place-autocomplete module. This minimal example will query for "Washington DC" and log the results to the Android Studio logcat.

Create a new Android project in Android Studio and follow these steps:

  1. Add the place-autocomplete and mapbox-search-android modules in your project's dependencies list in the app-level build.gradle (see the previous step).
  2. Add the code below to your MainActivty.kt file.
  3. Click File > Sync Project with Gradle Files
  4. Click the play button to build the app and run it on an emulator or device. The emulator will show a blank screen, but you can inspect the logcat output to see the search autocomplete results.
MainActivity.kt
package com.example.myapplication

import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.lifecycle.Lifecycle
import com.mapbox.search.autocomplete.PlaceAutocomplete
import com.mapbox.common.MapboxOptions
import kotlinx.coroutines.launch

class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)

// Set your Mapbox access token, reading from the string resource file
MapboxOptions.accessToken = getString(R.string.mapbox_access_token)
val placeAutocomplete = PlaceAutocomplete.create(locationProvider = null)

lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.CREATED) {
// get suggestions for the search query "Washington DC"
val response = placeAutocomplete.suggestions(query = "Washington DC")
if (response.isValue) {
val suggestions = response.value.orEmpty()
Log.i("SearchExample", "Suggestions: $suggestions")

if (suggestions.isNotEmpty()) {
val result = placeAutocomplete.select(suggestions.first())
result.onValue { Log.i("SearchExample", "Result: $it") }
result.onError { Log.e("SearchExample", "Error selecting suggestion", it) }
}
} else {
Log.e("SearchExample", "Error fetching suggestions: ${response.error}")
}
}
}
}
}
  1. Inspect the results in the Android Studio logcat by clicking the cat icon in the bottom left of the screen and searching for the PlaceAutocompleteResult object in the results. This object will contain information about the place, such as its name, coordinates, and address.
Logcat output
Result: PlaceAutocompleteResult(
id=dXJuOm1ieHBsYzpGSmlvN0E,
mapboxId=dXJuOm1ieHBsYzpGSmlvN0E,
name='Washington',
coordinate=Point{type=Point, bbox=null, coordinates=[-77.03938, 38.90253]},
routablePoints=null,
makiIcon=marker,
distanceMeters=null,
etaMinutes=null,
address=PlaceAutocompleteAddress(
houseNumber=null,
street=null,
neighborhood=null,
locality=null,
postcode=null,
place=Washington,
district=null,
region=District of Columbia,
country=United States,
formattedAddress=Washington,
District of Columbia,
United States,
countryIso1=null,
countryIso2=null
),
type=com.mapbox.search.autocomplete.PlaceAutocompleteType$AdministrativeUnit$Place@648264e,
categories=null,
phone=null,
website=null,
reviewCount=null,
averageRating=null,
openHours=null,
primaryPhotos=null,
otherPhotos=null
)

Next steps

Now that you have configured your app and installed the SDK dependencies, explore our guides and examples to learn how to add Search SDK features to your app:

See the full list of Search SDK examples to explore more ways to use the SDK in your app.

You can also explore the reference documentation for each module to learn more about the classes and methods available in the SDK.

この{Type}は役に立ちましたか?