We have just released a new Directions Library for Android. With this library you can easily add driving, walking, and cycling routes to your Android app, draw it on a map, and even detect when the user is off-route.
Installation
Like the Mapbox SDK, the library is readily available on Maven Central. Just add the following to your build.gradle
to start using it:
repositories {
mavenCentral()
}
dependencies {
compile ('com.mapbox.mapboxsdk:mapbox-android-directions:1.0.0@aar'){
transitive=true
}
}
Usage
Imagine that your app needs driving directions from downtown Los Angeles to the Santa Monica Pier. You can get the optimal route with only a few lines of code:
// Downtown LA
Waypoint origin = new Waypoint(-118.24233, 34.05332);
// Santa Monica Pier
Waypoint destination = new Waypoint(-118.49666, 34.01114);
// Build the client object
MapboxDirections client = new MapboxDirections.Builder()
.setAccessToken(MAPBOX_ACCESS_TOKEN)
.setOrigin(origin)
.setDestination(destination)
.setProfile(DirectionsCriteria.PROFILE_DRIVING)
.build();
// Execute the request
Response<DirectionsResponse> response = client.execute();
We’re using Square’s Retrofit under the hood, that means you can also do client.enqueue(callback)
if you prefer to execute the request asynchronously (safe to be called within your Activity).
It also means that you don’t need to deal with JSON parsing yourself, we take care of that. For example, this call will give you the total route distance as an int
:
DirectionsRoute route = response.body().getRoutes().get(0);
int distance = route.getDistance() // 26446 (in meters)
Draw the route on a map
You can also draw the route path on a Mapbox map. To get the same result as the image above, you’ll want to do something like this:
// Convert List<Waypoint> into LatLng[]
List<Waypoint> waypoints = route.getGeometry().getWaypoints();
LatLng[] points = new LatLng[waypoints.size()];
for (int i = 0; i < waypoints.size(); i++) {
points[i] = new LatLng(
waypoints.get(i).getLatitude(),
waypoints.get(i).getLongitude());
}
// Draw Points on MapView
mapView.addPolyline(new PolylineOptions()
.add(points)
.color(Color.parseColor("#3887be"))
.width(5));
That’s it.
Detect when the user is off-route
We provide a handy isOffRoute()
method that will calculate the distance between the user location and every waypoint in the route, to help you detect when the user might be off-route:
if (route.isOffRoute(userLocation)) {
Toast.makeText(this, "You are off-route.", Toast.LENGTH_SHORT).show();
}
On iOS, too
If you’re interested in iOS development, we also have Mapbox Directions for Swift, a drop-in replacement for Apple’s MKDirections API that doesn’t need MapKit.
Open Source
For more information on how to use this library check the code for the Directions Test App or visit our repository on GitHub.
Happy hacking.