Get Started with the Maps SDK for Android
This document describes the steps to install the latest stable version of the Maps SDK, add the Mapbox dependency to your map and quickly get a map up and running in your android application.
Prerequisites
- Mapbox account: Sign up or log into a free account on Mapbox.
- IDE for Android Development: A program to edit and build your Android application, like Android Studio.
Part 1: Create and configure your credentials
Before starting to develop your application with the Maps SDK, you'll need to create and configure your credentials.
Step 1: Log in/Sign up for a Mapbox account
If you haven't done so already, sign up for a Mapbox account and log into it.
You can sign up or sign in by clicking the buttons in the top right corner of your browser or going to https://account.mapbox.com/sign-up.
This account will allow you to create tokens and will create a default public token for you upon creation.
Step 2: Create a secret token
A secret token can enable access to various products/services at Mapbox, including the ability to download an SDK. To allow download access to an SDK, follow these steps:
- Go to your account's tokens page.
- Click the Create a token button.
- Name your token, for this example we've used InstallTokenAndroid.
- Scroll down to the Secret Scope section and check the
Downloads:Read
scope box. - Click the Create token button at the bottom of the page to create your token.
- Enter your password to confirm the creation of your token.
- 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.
This video also walks through the steps above:
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 (see next section).
Step 3: Configure your secret token
To avoid exposing your secret token, let's add it as an environment variable using gradle:
If you do not already have gradle installed, follow the Gradle Install guide to install gradle onto your computer.
To configure your secret token, follow these steps:
- Check if you already have a
gradle.properties
file in your Gradle user home folder.
- Open the Gradle user home folder at
/Users/USERNAME/.gradle
. - Note that you may not be able to see this folder and need to be reveal it.
- If on Mac, press
Command
+Shift
+.
to show hidden folders. - If on Windows, click
View
in the Explorer Window, and then clickShow > Hidden Items
.
- If on Mac, press
- With the folder revealed, you'll be able to open your
.gradle
folder and check for yourgradle.properties
file.
- If the
gradle.properties
file doesn't exist, create the file.- If you already have this file skip this step and go onto Step 3.
- For Mac, open a terminal in your .gradle folder and type
touch gradle.properties
. - For Windows, open a command window in your .gradle folder and type
echo >> gradle.properties
.
- Open your
gradle.properties
file and copy and paste the snippet below into the file:
MAPBOX_DOWNLOADS_TOKEN=YOUR_SECRET_MAPBOX_ACCESS_TOKEN
- Grab the secret token you made before and replace the text
YOUR_SECRET_MAPBOX_ACCESS_TOKEN
with the secret token.
More details about Gradle properties in the official Gradle documentation.
Step 4: Configure your public token
Next let's provide an access token to the SDK by adding the token as an Android string resource.
To do this, follow these steps:
- 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.
- Go to the folder structure in the left side of Android Studio and open your resource folder located at
app/res/values
. - Create a new resource file, by left clicking on the folder, selecting
New
>Values Resource File
- Name the file mapbox_access_token.xml and click the
Ok
button. - In the new file, copy and paste the code from below.
- Make sure your token is included in the code snippet. The token should start with the letter
pk
. If you seeYOUR_MAPBOX_ACCESS_TOKEN
in your code, log into your mapbox account and then copy the snippet again.- When you're logged into your account, your public mapbox token is automatically added to code snippet. You can also grab your default by going to your account's tokens page.
<?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>
Advanced Topics: Best Practices, Rotating Tokens & Adding Tokens at Runtime
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.
Step 5: Configure permissions
If you need to access user's location on the map or get the user's location information you will need to do the following:
- Open
app > manifests > AndroidManifest.mxl
- Determine the permissions you need. If you only need general user location access, add the
ACCESS_COARSE_LOCATION
permission. If also need access to a more precise location you will need to also callACCESS_FINE_LOCATION
.
- Note: You must call
ACCESS_COARSE_LOCATION
to access location at all, whileACCESS_FINE_LOCATION
is only needed for more specific access.
- Add the permissions you need as seen in the code snippet to the
AndroidManifest.xml
.
- This should be added at the top of the manifest, below the opening manifest tag and above the opening
<application>
tag.
You can check whether the user has granted location permission and request permissions if the user hasn't granted them yet using the PermissionsManager
.
Part 2: Add the dependency
Now that we have our credentials, let's add the dependency to our project.
Mapbox provides the Maps SDK via Maven.
To add the Mapbox Maps SDK as a dependency, you will need to configure your build to download the Maps SDK from Mapbox maven repository directly.
Access to the Mapbox repository requires a valid username and password. In the previous section, you added the password to your gradle.properties
file (see Part 1: Create and configure your credentials ) so now let's access the remote repository with that token:
- On the left side of Android Studio, in the file hierarchy, go to your project's
settings.gradle
file under theGradle Scripts
section and open your top levelsettings.gradle.kts
file. - Add a new
maven {...}
definition inside thedependencyResolutionManagement.repositories
. The hidden sections of the snippet below mimic thesettings.gradle.kts
file so you can see exactly where to place the snippet below:
- Open up your module-level (for example
app
>GradleScripts
>build.gradle.kts
) Gradle configuration file and make sure that your project'sminSdk
is 21 or higher:
android {
...
defaultConfig {
minSdk 21
...
}
}
android {
...
defaultConfig {
minSdk = 21
...
}
}
- Add the Mapbox SDK for Android dependency in the same module-level (for example
app
>GradleScripts
>build.gradle.kts
) Gradle configuration file:
dependencies {
...
implementation 'com.mapbox.maps:android:11.7.1'
...
}
dependencies {
...
implementation("com.mapbox.maps:android:11.7.1")
...
}
- (Optional) If you are using Jetpack Compose to build your app, add the Mapbox SDK Jetpack Compose Extension dependency in your module-level (for example
app/build.gradle.kts
) Gradle configuration file:
android {
buildFeatures {
compose true
}
composeOptions {
kotlinCompilerExtensionVersion = "1.3.2"
}
}
dependencies {
...
implementation 'com.mapbox.maps:android:11.7.1'
// If you're using compose also add the compose extension
implementation 'com.mapbox.extension:maps-compose:11.7.1'
...
}
android {
buildFeatures {
compose = true
}
composeOptions {
kotlinCompilerExtensionVersion = "1.3.2"
}
}
dependencies {
...
implementation("com.mapbox.maps:android:11.7.1")
// If you're using compose also add the compose extension
implementation("com.mapbox.extension:maps-compose:11.7.1")
...
}
- Because you've edited your Gradle files, click File > Sync Project with Gradle Files in Android Studio.
- You might have conflicting transitive dependencies. If necessary, you can use
exclude group
to remove certain dependencies (see Exclude transitive dependencies)_ - The username field in the
settings.gradle.kts
file should always be"mapbox"
. - Try running File > Sync Project with Gradle Files in case a change had not been synced throughout your project.
Part 3: Add a map
Let's add a map to our application. This can be accomplished one of 3 ways:
Jetpack Compose
Jetpack Compose
You can use Mapbox Maps compose extension to add a map to your composable.
To do make sure the following line is included in your dependencies
in the build.gradle.kts
file:
implementation ("com.mapbox.extension:maps-compose:11.6.0")
Then add the following code block to your MainActivity.kt
file.
package com.mapbox.maps.demo
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.ui.Modifier
import com.mapbox.geojson.Point
import com.mapbox.maps.extension.compose.MapboxMap
import com.mapbox.maps.extension.compose.animation.viewport.rememberMapViewportState
public class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MapboxMap(
Modifier.fillMaxSize(),
mapViewportState = rememberMapViewportState {
setCameraOptions {
zoom(2.0)
center(Point.fromLngLat(-98.0, 39.5))
pitch(0.0)
bearing(0.0)
}
},
)
}
}
}
Working with Jetpack Compose Extension
The Mapbox Jetpack Compose Extension wraps the MapView
. Since not all APIs are exposed through the Jetpack Compose Extension, you can get a reference to the MapView
to access the full API surface within a MapEffect
.
MapView
APIs within a MapEffect
can introduce internal state changes that may conflict with Compose states, potentially leading to unexpected or undefined behavior.The following example showcases how to turn on debug features using MapEffect
:
Compass
, Scalebar
, Logo
, Attribution
, and Lifecycle
—are replaced by their Jetpack Compose counterparts. As a result, APIs such as mapView.compass
, mapView.scalebar
, mapView.logo
, mapView.attribution
, and mapView.lifecycle
will not function and may result in runtime exceptions. To avoid these issues, use the corresponding Compose APIs instead.Layouts in views: Using XML
XML Layout
Open the activity's XML layout file and add the com.mapbox.maps.MapView
element inside your layout:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.mapbox.maps.MapView
android:id="@+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:mapbox_cameraTargetLat="39.5"
app:mapbox_cameraTargetLng="-98.0"
app:mapbox_cameraZoom="2.0"
app:mapbox_cameraPitch="0.0"
app:mapbox_cameraBearing="0.0" />
</FrameLayout>
Layouts in views: Instantiating at runtime
After following on of the methods above, you should be able to press the play button above your code to start the emulator. After spinning up, the emulator should show a map like so:
If your implementation is not working as expected, check our troubleshooting section:
Troubleshooting
- The username field in the
settings.gradle.kts
file should always be"mapbox"
. - Click on File > Save All to make sure you haven't missed any changes.
- Try running File > Sync Project with Gradle Files in case a change had not been synced throughout your project.
- If the mapbox library isn't being imported, check the following:
- Check
app/res/values/mapbox_access_token.xml
has a token and does not sayYOUR_MAPBOX_ACCESS_TOKEN
. - Make sure you've added the required dependencies to the
settings.gradle.kts
file andbuild.gradle.kts
match the example snippets seen in Part 2: Add the dependency.
- Check
- Check you've imported the right libraries into the MainActivity file as seen in the example code.
- Switch virtual devices if you can't get your map to show on the default pixel fold.
- Check if you have conflicting transitive dependencies. If necessary, you can use
exclude group
to remove certain dependencies (see Exclude transitive dependencies)_
Next Steps
Now that you have your map up and running, read our other Android content:
Learn how to add default markers to your map.
Learn how to find a user's location, understand privacy rights, and how to add user location features to your app.