Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions android-navigation/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
## Add turn-by-turn navigation to an Android app

This repo is a demo application to help developers understand how to use [Mapbox Navigation SDK for Android](https://docs.mapbox.com/android/navigation/) in an Android application using Kotlin and Jetpack Compose.

The corresponding walk-through tutorial is available on [docs.mapbox.com](https://docs.mapbox.com/help/tutorials/android-navigation/).

The app demonstrates the use of [`NavigationView`](https://docs.mapbox.com/android/navigation/v2/guides/drop-in-ui/integrate-drop-in-ui/) as a "drop-in" navigation experience for Android. The user can choose from a list of predefined destinations. Tapping one passes the current device location coordinates and the destination coordinates to `NavigationLoader`, which calculates routes. The routes are then used to render `NavigationView`, which presents turn-by-turn navigation with voice prompts in a fullscreen view.

### Requirements
- A [Mapbox Account](https://console.mapbox.com) and Access Token
- Android Studio

#### Configure your download token
Mapbox's Navigation SDK is hosted on a private Maven repository, so getting the project to build requires a **secret** token with the `Downloads:Read` scope, used only by Gradle to download the SDK. Add it to `~/.gradle/gradle.properties` (outside this repo, never committed):
```properties
MAPBOX_DOWNLOADS_TOKEN=YOUR_SECRET_TOKEN
```

#### Configure your public access token
In the project explorer, right-click the `app/src/main/res/values` folder and select **New > Values Resource File**, name it `mapbox_access_token.xml`, and add your public access token:

`app/src/main/res/values/mapbox_access_token.xml`
```xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="mapbox_access_token" translatable="false">YOUR_MAPBOX_ACCESS_TOKEN</string>
</resources>
```

Find both tokens in the [Mapbox Console](https://console.mapbox.com).
1 change: 1 addition & 0 deletions android-navigation/app/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/build
64 changes: 64 additions & 0 deletions android-navigation/app/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
plugins {
alias(libs.plugins.android.application)
alias(libs.plugins.kotlin.compose)
}

android {
namespace = "com.example.nav_turn_tutorial"
compileSdk {
version = release(37) {
minorApiLevel = 0
}
}

defaultConfig {
applicationId = "com.example.nav_turn_tutorial"
minSdk = 24
targetSdk = 36
versionCode = 1
versionName = "1.0"

ndk {
abiFilters += listOf("arm64-v8a", "x86_64")
}

testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}

buildTypes {
release {
isMinifyEnabled = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
}
buildFeatures {
compose = true
}
}

dependencies {
implementation(platform(libs.androidx.compose.bom))
implementation(libs.androidx.activity.compose)
implementation(libs.androidx.compose.material3)
implementation(libs.androidx.compose.ui)
implementation(libs.androidx.compose.ui.graphics)
implementation(libs.androidx.compose.ui.tooling.preview)
implementation(libs.androidx.core.ktx)
implementation(libs.androidx.lifecycle.runtime.ktx)
implementation(libs.mapbox.navigation.ui.dropin)
implementation(libs.play.services.location)
testImplementation(libs.junit)
androidTestImplementation(platform(libs.androidx.compose.bom))
androidTestImplementation(libs.androidx.compose.ui.test.junit4)
androidTestImplementation(libs.androidx.espresso.core)
androidTestImplementation(libs.androidx.junit)
debugImplementation(libs.androidx.compose.ui.test.manifest)
debugImplementation(libs.androidx.compose.ui.tooling)
}
21 changes: 21 additions & 0 deletions android-navigation/app/proguard-rules.pro
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html

# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}

# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable

# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.example.nav_turn_tutorial

import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4

import org.junit.Test
import org.junit.runner.RunWith

import org.junit.Assert.*

/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.nav_turn_tutorial", appContext.packageName)
}
}
34 changes: 34 additions & 0 deletions android-navigation/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_LOCATION" />

<application
android:name=".NavTutorialApplication"
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Navturntutorial">
<activity
android:name=".MainActivity"
android:exported="true"
android:label="@string/app_name"
android:theme="@style/Theme.Navturntutorial">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.example.nav_turn_tutorial

import com.mapbox.geojson.Point

data class Destination(
val name: String,
val point: Point
)

val destinations = listOf(
Destination("Statue of Liberty", Point.fromLngLat(-74.0445, 40.6892)),
Destination("Empire State Building", Point.fromLngLat(-73.9857, 40.7484)),
Destination("Central Park", Point.fromLngLat(-73.9654, 40.7829))
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
package com.example.nav_turn_tutorial

import android.Manifest
import android.content.pm.PackageManager
import android.util.Log
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.core.content.ContextCompat
import com.google.android.gms.location.LocationServices
import com.google.android.gms.location.Priority
import com.google.android.gms.tasks.CancellationTokenSource
import com.mapbox.geojson.Point
import kotlinx.coroutines.launch

private const val TAG = "DestinationList"

@Composable
fun DestinationListScreen(
modifier: Modifier = Modifier,
onNavigationReady: (PreparedNavigation) -> Unit
) {
val context = LocalContext.current
val scope = rememberCoroutineScope()
val navigationLoader = remember { NavigationLoader(context) }
val fusedLocationClient = remember { LocationServices.getFusedLocationProviderClient(context) }

var hasLocationPermission by remember {
mutableStateOf(
ContextCompat.checkSelfPermission(
context,
Manifest.permission.ACCESS_FINE_LOCATION
) == PackageManager.PERMISSION_GRANTED
)
}
var isLoadingRoute by remember { mutableStateOf(false) }

val permissionLauncher = rememberLauncherForActivityResult(
ActivityResultContracts.RequestMultiplePermissions()
) { grants ->
hasLocationPermission = grants[Manifest.permission.ACCESS_FINE_LOCATION] == true
}

fun requestRouteTo(destination: Destination) {
if (!hasLocationPermission) {
permissionLauncher.launch(
arrayOf(
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION
)
)
return
}
isLoadingRoute = true
fusedLocationClient.getCurrentLocation(
Priority.PRIORITY_HIGH_ACCURACY,
CancellationTokenSource().token
).addOnSuccessListener { location ->
if (location == null) {
Log.w(TAG, "Current location unavailable")
isLoadingRoute = false
return@addOnSuccessListener
}
val origin = Point.fromLngLat(location.longitude, location.latitude)
Log.d(TAG, "Origin: $origin, Destination: ${destination.point}")
scope.launch {
val prepared = navigationLoader.loadNavigation(origin, destination.point)
Log.d(TAG, "Route distance: ${prepared.distanceMeters} meters")
isLoadingRoute = false
onNavigationReady(prepared)
}
}
}

Column(modifier = modifier.fillMaxSize().padding(16.dp)) {
Text(text = "Choose a destination")
LazyColumn(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
items(destinations) { destination ->
Button(
onClick = { requestRouteTo(destination) },
enabled = !isLoadingRoute
) {
Text(destination.name)
}
}
}
if (isLoadingRoute) {
CircularProgressIndicator(modifier = Modifier.padding(top = 16.dp))
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package com.example.nav_turn_tutorial

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import com.example.nav_turn_tutorial.ui.theme.NavturntutorialTheme

class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
NavturntutorialTheme {
Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
NavTutorialApp(modifier = Modifier.padding(innerPadding))
}
}
}
}
}

@Composable
fun NavTutorialApp(modifier: Modifier = Modifier) {
var preparedNavigation by remember { mutableStateOf<PreparedNavigation?>(null) }

val navigation = preparedNavigation
if (navigation == null) {
DestinationListScreen(
modifier = modifier,
onNavigationReady = { preparedNavigation = it }
)
} else {
NavigationScreen(
routes = navigation.routes,
simulateRoute = true,
onExit = { preparedNavigation = null }
)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.example.nav_turn_tutorial

import android.app.Application
import com.mapbox.navigation.base.options.NavigationOptions
import com.mapbox.navigation.core.lifecycle.MapboxNavigationApp

class NavTutorialApplication : Application() {
override fun onCreate() {
super.onCreate()
if (!MapboxNavigationApp.isSetup()) {
val accessTokenResId = resources.getIdentifier(
"mapbox_access_token",
"string",
packageName
)
MapboxNavigationApp.setup(
NavigationOptions.Builder(this)
.accessToken(getString(accessTokenResId))
.build()
)
}
MapboxNavigationApp.attachAllActivities(this)
}
}
Loading