Skip to main content

Custom routes

A newer version of the Navigation SDK is available
This page uses v1.6.2 of the Mapbox Navigation SDK. A newer version of the SDK is available. Learn about the latest version, v2.20.2, in the Navigation SDK documentation.

In some cases, you may want your user to navigate along a route that doesn't match the Mapbox Directions API route's structure, while still using the Mapbox Navigation SDK. Mapbox Java SDK's Map Matching API wrapper is an appropriate tool for turning your custom route into a route that the Navigation SDK can process.

Map match to generate a route

Map matching is the art of taking coordinates and aligning them along a road network. After providing coordinates to the Java SDK's MapboxMapMatching.builder(), the Java SDK makes the request to the Mapbox Map Matching API, and then the API returns a route that can be used in the Navigation SDK for Android.

To get started with creating a map matched DirectionsRoute, first install the Java SDK's services module into your project.

Your MapboxMapMatching request will need a List of Point geometry objects that represent the custom route you want to match with the road network.

val singlePoint = Point.fromLngLat()

Create a MapboxMapMatching request:

val mapboxMapMatchingRequest = MapboxMapMatching.builder()
.accessToken(getString(R.string.mapbox_access_token))
.coordinates(customRoutePointList)
.steps(true)
.voiceInstructions(true)
.bannerInstructions(true)
.profile(DirectionsCriteria.PROFILE_DRIVING)
.build()

If successful, the response will have a matched route. Convert this route to a DirectionsRoute and give it to the already-instantiated MapboxNavigation object:

mapboxMapMatchingRequest.enqueueCall(object : Callback<MapMatchingResponse> {
override fun onResponse(call: Call<MapMatchingResponse>, response: Response<MapMatchingResponse>) {
if (response.isSuccessful) {
response.body()?.matchings()?.let { matchingList ->
matchingList[0].toDirectionRoute().apply {
mapboxNavigation?.setRoutes(listOf(this))
}
}

}
}

override fun onFailure(call: Call<MapMatchingResponse>, throwable: Throwable) {

}
})
mobile Navigation UI SDK

When using MapboxMapMatching with the Navigation SDK, you need to make a few changes to your setup to make sure re-routes are successful. Set a custom RerouteController to your MapboxNavigation or rerouting needs to be disabled entirely. Otherwise, Navigation SDK would try to request a new route directly from Mapbox Directions API. For more details, go to the off-route documentation.

EXAMPLE
Map matching

See how to use the Java SDK's Map Matching API wrapper to match points to the world's road and path network.