Directions
The Mapbox Directions API delivers routes for navigating the world. Use the Mapbox Java SDK's wrapper around the Directions API to build a request and process the API response for driving, walking, or cycling directions.
For more information about this API, including its pricing structure, see the Mapbox Directions API documentation. Along with the API documentation, you can also view various Mapbox Android demo app examples that use the Directions API to see complete examples of how to use the API.
Installation
The Directions API can be used completely on its own to get routes and other directional information. Built on top of the Directions API, the Mapbox Navigation SDK for Android enables you to interact with and use the information inside of the Directions API response. Use the Mapbox Java Services dependency if you want to use the Mapbox Directions API without using the entire Mapbox Navigation SDK.
implementation 'com.mapbox.mapboxsdk:mapbox-sdk-services:7.3.0'
Building a request
The Mapbox Directions API requires you to build a URL with various parameters to request the information that you want. This URL has required and optional parameters. The MapboxDirections.Builder()
class helps you set these various parameters.
The three required parameters are:
- an origin
Point
object - a destination
Point
object - a routing profile
MapboxDirections client = MapboxDirections.builder()
.origin(origin)
.destination(destination)
.overview(DirectionsCriteria.OVERVIEW_FULL)
.profile(DirectionsCriteria.PROFILE_DRIVING)
.accessToken(MAPBOX_ACCESS_TOKEN)
.build();
val client = MapboxDirections.builder()
.origin(origin)
.destination(destination)
.overview(DirectionsCriteria.OVERVIEW_FULL)
.profile(DirectionsCriteria.PROFILE_DRIVING)
.accessToken(MAPBOX_ACCESS_TOKEN)
.build()
Profiles:
- Traffic: For automotive routing. This profile factors in current and historical traffic conditions to avoid slowdowns. Traffic information is available in these supported geographies.
- Driving: For automotive routing. This profile shows the fastest routes by preferring high-speed roads like highways.
- Walking: For pedestrian and hiking routing. This profile shows the shortest path by using sidewalks and trails.
- Cycling: For bicycle routing. This profile shows routes that are short and safer for cyclists by avoiding highways and preferring streets with bike lanes.
For additional information on all the available optional parameters, see the Directions API documentation.
Directions API requests for driving, walking, and cycling routes can specify up to 25 total waypoints along the route.
Requests using the traffic profile can specify up to 3 waypoints.
- Traffic coverage for the traffic profile is available in supported geographies. Requests to this profile revert to driving profile results for areas without traffic coverage.
- Maximum 60 requests per minute.
- Computing route alternatives is not supported on the traffic profile.
Handling the response
You can access the Directions API's response inside of the onResponse
callback. The callback is a Retrofit callback, like all the Mapbox Java SDK's other API calls.
The response object will include:
-
an array of waypoint objects. Each waypoint is an input coordinate snapped to the road and path network. The waypoints appear in the array in the order of the input coordinates. (
DirectionsWaypoint
is the Java class). For more information about the waypoint object, see the Directions API documentation. -
An array of route objects ordered by descending recommendation rank. The response object may contain at most 2 routes. (
DirectionsRoute
is the Java class). For more information about the route object, see the Directions API documentation.
client.enqueueCall(new Callback<DirectionsResponse>() {
@Override public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
if (response.body() == null) {
Log.e("No routes found, make sure you set the right user and access token.");
return;
} else if (response.body().routes().size() < 1) {
Log.e("No routes found");
return;
}
// Retrieve the directions route from the API response
currentRoute = response.body().routes().get(0);
}
@Override public void onFailure(Call<DirectionsResponse> call, Throwable throwable) {
Log.e(TAG, "Error: " + throwable.getMessage());
}
});
client?.enqueueCall(object : Callback<DirectionsResponse> {
override fun onResponse(call: Call<DirectionsResponse>, response: Response<DirectionsResponse>) {
if (response.body() == null) {
Log.e("No routes found, make sure you set the right user and access token.")
return
} else if (response.body()!!.routes().size < 1) {
Log.e("No routes found")
return
}
// Get the directions route
val response = response
val currentRoute = response.body()!!.routes()[0]
}
override fun onFailure(call: Call<DirectionsResponse>, throwable: Throwable) {
Log.e("Error: " + throwable.message)
})
Build a Directions API request and see the results on a map.
Read the full documentation on the Mapbox Directions API to learn more. The Java SDK's Services dependency has equivalent Java classes for the various objects and information in the full Directions API response. Each object has a .Builder()
class as well. For example:
RouteLeg routeLeg = RouteLeg.builder()
.annotation(LegAnnotation)
.summary(summaryString)
.build();
val routeLeg = RouteLeg.builder()
.annotation(LegAnnotation)
.summary(summaryString)
.build()
VoiceInstructions voiceInstructions = VoiceInstructions.builder()
.distanceAlongGeometry(Double distanceAlongGeometry)
.build();
val voiceInstructions = VoiceInstructions.builder()
.distanceAlongGeometry(Double distanceAlongGeometry)
.build()
Once you have a successful Directions API response (response.body()
), as discussed above, you will be able to parse through the information to access the specific information that you want.
Drawing the route
You might want to draw the directions route on a map if you're using the Java SDK's Directions API. Using the route's geometry to create a LineString
is the key to making this happen.
Feature directionsRouteFeature = Feature.fromGeometry(LineString.fromPolyline(currentRoute.geometry(), PRECISION_6));
val directionsRouteFeature = Feature.fromGeometry(LineString.fromPolyline(currentRoute.geometry(), PRECISION_6))
Once you've created a Feature
for which the geometry is a LineString
, you can then use it with the FeatureCollection
, GeoJsonSource
, and LineLayer
objects.
This is called data-driven styling. For more information about how data-driven styling can be used in a map, see the styling layers guide.
Use the Java SDK to retrieve a route between two locations and display it on a map.