Sorry, you need to enable JavaScript to visit this website.

Routing Examples

Routing Examples

Have a look at our functional examples to see how to implement search features with Maps SDK.

Speed up development by using our sample code snippets in your app. Try all of this out with the Maps SDK Examples app!

Travel modes

Allow your users to plan a route for different travel modes.

Sample use case: You want to check what travel mode (car or truck) gives you the best ETA for a trip from Amsterdam to Rotterdam.

Available travel modes:

travelMode = TravelMode.CAR
travelMode = TravelMode.TRUCK
travelMode = TravelMode.TAXI
travelMode = TravelMode.BUS
travelMode = TravelMode.VAN
travelMode = TravelMode.MOTORCYCLE
travelMode = TravelMode.BICYCLE
travelMode = TravelMode.PEDESTRIAN
travelMode = TravelMode.OTHER

To request for a specified travel mode:

RouteQuery queryBuilder = RouteQueryBuilder.create(getRouteConfig().getOrigin(), getRouteConfig().getDestination())
        .withMaxAlternatives(0)
        .withReport(Report.EFFECTIVE_SETTINGS)
        .withInstructionsType(InstructionsType.TEXT)
        .withTravelMode(travelMode)
        .withConsiderTraffic(false).build();


image

Travel mode car

image

Travel mode pedestrian

image

Travel mode truck

Route types

Allow your users to plan a route that will be the fastest, shortest, most thrilling or the environment friendly.

Sample use case: You plan a trip from Amsterdam to Rotterdam and want to compare ETAs for different types of routes to choose the best fit your preferences.

Available route types:

routeType = RouteType.FASTEST
routeType = RouteType.SHORTEST
routeType = RouteType.ECO
routeType = RouteType.THRILLING

To request a route for a specified travel type:

RouteQueryBuilder queryBuilder = RouteQueryBuilder.create(getRouteConfig().getOrigin(), getRouteConfig().getDestination())
        .withMaxAlternatives(0)
        .withReport(Report.EFFECTIVE_SETTINGS)
        .withInstructionsType(InstructionsType.TEXT)
        .withRouteType(routeType)
        .withConsiderTraffic(false);
return queryBuilder.build();


image

Route type eco

image

Route type fastest

image

Route type shortest

Route avoids

Allow your users to plan a route that avoids things like toll roads, motorways, ferries, unpaved roads, carpool lanes,
roads that they have already taken, vignettes or even whole areas.

Sample use case: You plan a trip between the TomTom offices in Amsterdam and Oslo.
You would like to check how much time you gain by taking a ferry and how much more
time it will take to drive if you don’t use motorways so you can choose the best route for you.

Available routes to avoid:

routeAvoid = Avoid.TOLL_ROADS
routeAvoid = Avoid.MOTORWAYS
routeAvoid = Avoid.FERRIES
routeAvoid = Avoid.UNPAVED_ROADS
routeAvoid = Avoid.CAR_POOLS
routeAvoid = Avoid.ALREADY_USED_ROADS

To request a route for a specified route avoid:

RouteQuery queryBuilder = RouteQueryBuilder.create(getRouteConfig().getOrigin(), getRouteConfig().getDestination())
        .withMaxAlternatives(0)
        .withReport(Report.NONE)
        .withInstructionsType(InstructionsType.NONE)
        .withAvoidType(routeAvoid)
        .withConsiderTraffic(false).build();


image

Route avoid ferries

image

Route avoid motorways

image

Route avoid toll roads

Sample use case: You plan a trip from A to B and you know that on your way there are vignettes.
Additionally, there is an area which has a very high traffic. You want to avoid both vignettes and the specified area.

To avoid vignettes:

List<String> avoidVignettesList = new ArrayList<>();
avoidVignettesList.add("HUN");
avoidVignettesList.add("CZE");
avoidVignettesList.add("SVK");

RouteQuery routeQuery = createRouteQueryBuilderWithChosenParams(origin, destination)
        .withAvoidVignettes(avoidVignettesList)
        .build();

To avoid an area:

BoundingBox boundingBox = new BoundingBox(ARAD_TOP_LEFT_NEIGHBORHOOD, ARAD_BOTTOM_RIGHT_NEIGHBORHOOD);

RouteQuery routeQuery = createRouteQueryBuilderWithChosenParams(origin, destination)
        .withAvoidArea(boundingBox)
        .build();


image

Route without avoiding anything

image

Route with avoiding specified area

image

Route with avoiding vignettes

Routing with waypoints

Allow your users to plan a route with up to 50 waypoints. Help your users to get the best route through all their stops in the optimal order.

Sample use case: You plan a trip from the TomTom office in Amsterdam to the office in Berlin. There are a few places that you would like to visit during the drive. You would like to check if your preferred route is the best way to visit all of the places in the shortest time. To do this, input the coordinates as waypoints and call the routing module using the withComputeBestOrder parameter.

To request a route with waypoints:

LatLng[] wayPointsArray = wayPoints.toArray(new LatLng[wayPoints.size()]);
RouteQuery routeQuery = RouteQueryBuilder.create(getRouteConfig().getOrigin(), getRouteConfig().getDestination())
        .withWayPoints(wayPointsArray)
        .withComputeBestOrder(computeBestOrder)
        .withConsiderTraffic(false).build();


image

Initial_order

image

Best order

image

No waypoints

Routing with departure/arrival time

Allow your users to get a route planned for specific arrival and departure time so they can use this
information to adjust their commute plans.

Sample use case: You have a busy schedule and you need to plan your day optimally.
You can use the arrival at option to learn when you need to depart to be at a specific time at a
specific place. You can use depart at to know the time of arrival to the place you have your next appointment at.

In the example below you can see an implementation of using the arrive at and depart at parameters for
a trip from Amsterdam to Berlin using departAt parameters.
The departAt value must be in the future. The departAt parameter can not be used in conjunction with arriveAt.

return RouteQueryBuilder.create(getRouteConfig().getOrigin(), getRouteConfig().getDestination())
        .withReport(Report.EFFECTIVE_SETTINGS)
        .withInstructionsType(InstructionsType.TEXT)
        .withDepartAt(departureTime)
        .withConsiderTraffic(false).build();

The date and time of arrival at the destination point must be specified as a dateTime.
The arriveAt value must be in the future. The arriveAt parameter cannot be used in conjunction with departAt,
minDeviationDistance or minDeviationTime. It cannot be used in calculateReachableRange requests.

return RouteQueryBuilder.create(getRouteConfig().getOrigin(), getRouteConfig().getDestination())
        .withReport(Report.EFFECTIVE_SETTINGS)
        .withInstructionsType(InstructionsType.TEXT)
        .withArriveAt(arrivalTime)
        .withConsiderTraffic(false).build();

Routing with alternative routes

Allow your users to check different routing alternatives so they can choose the one they prefer.

Sample use case: You are preparing a road trip and you would like to see different route options so you can choose one that is both optimal for your trip and suits your road trip preferences.

In the example below, you can see an implementation of alternative routes using a clickable route object. Click on the route to get its ETA and the distance between its origin and destination.

To request a route with alternatives:

RouteQuery queryBuilder = RouteQueryBuilder.create(getRouteConfig().getOrigin(), getRouteConfig().getDestination())
        .withMaxAlternatives(maxAlternatives)
        .withReport(Report.EFFECTIVE_SETTINGS)
        .withInstructionsType(InstructionsType.TEXT)
        .withConsiderTraffic(false).build();


image

One alternative route

image

Three alternative routes

image

Five alternative routes

Routing with language parameter

Allow your user to get results in different languages to make your app international.
The language parameter determines the language of the guidance messages.
It does not affect proper nouns (the names of streets, plazas, etc.)

Sample use case: You are planning a journey and you want to have the list of
instructions in different languages.

To request a route using language parameter:

RouteQuery queryBuilder = RouteQueryBuilder.create(getRouteConfig().getOrigin(), getRouteConfig().getDestination())
        .withLanguage(language)
        .withReport(Report.EFFECTIVE_SETTINGS)
        .withInstructionsType(InstructionsType.TEXT)
        .withConsiderTraffic(false).build();

Maneuver list

Serve your users with list of maneuvers (driving instructions) with turn by turn information for every
maneuver. You can get the maneuvers in different languages to make your app
international.

Sample use case: You are planning a journey and you want to have the list of
maneuvers so you can always look them up en route.

In the example below, you can see an implementation of maneuver list that
is available in English, German, Spanish and French. You can select the language
while building 'FullRoute' object.

protected void displayInfoAboutRoute(FullRoute routeResult) {
    super.displayInfoAboutRoute(routeResult);
    List<Instruction> instructions = Arrays.asList(routeResult.getGuidance().getInstructions());
    maneuversFragment.updateInstructions(instructions);
}


image

English

image

German

image

Spanish

Consumption model

Allow your user to utilise the vehicle-specific consumption model when requesting a new route.
The consumption model can be calculated based on a number of Online Routing API
parameters for two vehicle types: combustion or electric and the output will
contain the additional field fuelConsumptionInLiters or batteryConsumptionInkWh.
For more details, please refer to: this documentation.

Sample use case: You are planning a journey and you want to select the most optimal route
in terms of fuel / energy consumption.

To request a route and calculate consumption model for combustion vehicle:

RouteQuery queryBuilder = RouteQueryBuilder.create(getRouteConfig().getOrigin(), getRouteConfig().getDestination())
        .withConsiderTraffic(false)
        .withMaxAlternatives(2)
        .withVehicleWeightInKg(1600) //vehicle weight in kilograms
        .withCurrentFuelInLiters(50.0)
        .withAuxiliaryPowerInLitersPerHour(0.2)
        .withFuelEnergyDensityInMJoulesPerLiter(34.2)
        .withAccelerationEfficiency(0.33) //e.g. KineticEnergyGained/ChemicalEnergyConsumed
        .withDecelerationEfficiency(0.33) //e.g. ChemicalEnergySaved/KineticEnergyLost
        .withUphillEfficiency(0.33) //e.g. PotentialEnergyGained/ChemicalEnergyConsumed
        .withDownhillEfficiency(0.33) //e.g. ChemicalEnergySaved/PotentialEnergyLost
        .withVehicleEngineType(VehicleEngineType.COMBUSTION)
        .withConstantSpeedConsumptionInLitersPerHundredKm(SpeedToConsumptionMap.create(ImmutableMap.<Integer, Double>builder()
                //vehicle specific consumption model <speed, consumption in liters>
                .put(10, 6.5)
                .put(30, 7.0)
                .put(50, 8.0)
                .put(70, 8.4)
                .put(90, 7.7)
                .put(120, 7.5)
                .put(150, 9.0)
                .build())
        ).build();

To request a route and calculate consumption model for electric vehicle:

RouteQuery queryBuilder = RouteQueryBuilder.create(getRouteConfig().getOrigin(), getRouteConfig().getDestination())
        .withConsiderTraffic(false)
        .withMaxAlternatives(2)
        .withVehicleWeightInKg(1600) //vehicle weight in kilograms
        .withCurrentChargeInKWh(43.0)
        .withMaxChargeInKWh(85.0)
        .withAuxiliaryPowerInKW(1.7)
        .withAccelerationEfficiency(0.33) //e.g. KineticEnergyGained/ChemicalEnergyConsumed
        .withDecelerationEfficiency(0.33) //e.g. ChemicalEnergySaved/KineticEnergyLost
        .withUphillEfficiency(0.33) //e.g. PotentialEnergyGained/ChemicalEnergyConsumed
        .withDownhillEfficiency(0.33) //e.g. ChemicalEnergySaved/PotentialEnergyLost
        .withVehicleEngineType(VehicleEngineType.ELECTRIC)
        .withConstantSpeedConsumptionInKWhPerHundredKm(SpeedToConsumptionMap.create(ImmutableMap.<Integer, Double>builder()
                //vehicle specific consumption model <speed, consumption in kWh>
                .put(10, 5.0)
                .put(30, 10.0)
                .put(50, 15.0)
                .put(70, 20.0)
                .put(90, 25.0)
                .put(120, 30.0)
                .build())
        ).build();


image

Combustion

image

Electric

Supporting points

Allow your user to reconstruct his/her route using supporting points. Supporting points
can be combined with minDeviationDistance or minDeviationTime constraints. When these constraints are used,
the alternative routes will follow the reference route from the origin point for the given time or distance.
In other words, alternative routes just diverge from the reference route after the given constraints.
When using supporting points, intermediate locations (waypoints) are not supported.

Sample use case: You have route coordinates saved on your device.
You want to reconstruct the route based on the coordinates (supporting points)
and calculate zero or more alternative routes to this reference route.

To request a route with supporting points support:

RouteQuery queryBuilder = RouteQueryBuilder.create(EXAMPLE_ORIGIN, EXAMPLE_DESTINATION)
        .withMaxAlternatives(1)
        .withMinDeviationTime(0)
        .withSupportingPoints(SUPPORTING_POINTS)
        .withMinDeviationDistance(minDeviationDistance)
        .withConsiderTraffic(false).build();


image

Min. deviation distance: 0 m

image

Min. deviation distance: 10 km

Reachable range

The Reachable Range component calculates a set of locations that can be reached from the origin point. It optimizes for routes with a given route-type (e.g. fastest, eco, etc) but limits the range for the given budget and consumption parameters.
It uses Calculate Reachable Range API so you can find all details in the service documentation.

Sample use case: You are preparing to a trip and you would like to check how far you can drive on your battery or tank, or within specific time limit so you plan your journey.

The example below shows a number of points that are reachable based on one of specified model for:
* Combustion engine
* Electric engine
* Time-2h limit on an electric car (time budget model is available for both electric and combustion engines)

Use the code sample below for implementing a similar use case.

To request a reachable range create a ReachableRangeQuery:

return ReachableRangeQueryBuilder.create(Locations.AMSTERDAM_CENTER_LOCATION)
        .withFuelBudgetInLiters(5.0)

and pass it to the routing API:

routingApi.findReachableRange(
        reachableRangeQueryFactory.createReachableRangeQueryForCombustion(),
        reachableRangeResultListener);

Setup of the common params for reachable range query:

                .withVehicleWeightInKg(1600)
                .withCurrentFuelInLiters(43.0)
                .withFuelEnergyDensityInMJoulesPerLiter(34.2)
                .withAuxiliaryPowerInLitersPerHour(1.7)
                .withAccelerationEfficiency(0.33)
                .withDecelerationEfficiency(0.33)
                .withUphillEfficiency(0.33)
                .withDownhillEfficiency(0.33)
                .withConstantSpeedConsumptionInLitersPerHundredKm(consumption)
                .withVehicleEngineType(VehicleEngineType.COMBUSTION)
                .build();
    }

}

Setup of the reachable range specific params of query:

return ReachableRangeQueryBuilder.create(Locations.AMSTERDAM_CENTER_LOCATION)
        .withFuelBudgetInLiters(5.0)

The result can be observed with ReachableRangeResultListener:

protected ReachableRangeResultListener reachableRangeResultListener = new ReachableRangeResultListener() {
    @Override
    public void onReachableRangeResponse(ReachableRangeResponse response) {
        doActionOnReachableRangeResponse(response);
    }

    @Override
    public void onReachableRangeError(Throwable error) {
        doActionOnReachableRangeError();
    }
};


image

Fuel budget: 5 liters

image

Energy budget: 5 kWh

image

Time budget: 2h

You can use the output of the returned set of locations for other interacting use cases e.g. searching for places on the route to one (many) reachable point(s) with Search along the route or within the polygon boundaries with Geometry search features of Maps SDK.

Batch routing

Allow your users to send multiple synchronous routing requests with Batch Routing components. You can mix different
types of routing requests to compare them in an easy way.

Batch Routing components described use Online Batch Routing API
so you can find all details about it in the service documentation.

Sample use case: You are preparing to a trip and you would like to choose the most optimal route for your travel.
You would like to compare the ETA and distances for routes depending on travel modes, route types or avoids.

Also, you can adjust the batch request with other parameters described in Online Batch Routing API
or JavaDocs of this SDK under Api reference section.

The example below shows multiple routes requested in the batch. Each example sends three requests in one batch.
All examples allow a user to compare routes visually on the map, their ETAs and distances by clicking on a chosen route.

  • Travel mode example shows three routes: the route by car, the route by truck and the route as a pedestrian.

  • Route type example shows three routes: the fastest route, the shortest route and the most eco route.

  • Avoids example shows three routes: the avoid-motorways route, the avoid-ferries route and the avoid-toll roads.

Use the code sample below for implementing a similar use case.

To request a batch query create a BatchRoutingQuery:

return BatchRoutingQueryBuilder.create()
        .withRouteQuery(getTravelModeQuery(TravelMode.CAR))
        .withRouteQuery(getTravelModeQuery(TravelMode.TRUCK))
        .withRouteQuery(getTravelModeQuery(TravelMode.PEDESTRIAN))
        .build();

and pass it to the routing API:

Disposable subscribe = routePlannerAPI.planBatchRoute(query)

Setup of the common params for batch routing query:

return RouteQueryBuilder.create(getRouteConfig().getOrigin(), getRouteConfig().getDestination())
        .withTravelMode(travelMode).withMaxAlternatives(0)
        .withReport(Report.EFFECTIVE_SETTINGS)
        .withInstructionsType(InstructionsType.TEXT)
        .withConsiderTraffic(false)
        .build();

The result can be observed with listener or by rx java subscription:

/**
 * The listener for response of the query sent to Batch Routing online service.
 */
public interface BatchableRoutingResultListener {

    /**
     * Triggered when the response from the batch routing online service will be available.
     *
     * @param response - The information returned is a container for all route results.
     */
    void onBatchResult(BatchRoutingResponse response);

    /**
     * Triggered when the online request for batch routing failed.
     *
     * @param exception the exception returned when the request to service fails.
     */
    void onBatchError(ServiceException exception);
}


image

Travel modes: car, truck, pedestrian

image

Route type: fastest, shortest, eco

image

Avoids: motorways, ferries, toll roads

You can select route and get information about ETA and distances.

Sample use case: You are preparing the trip for the weekend and you want to check how far you can get by electric car, electric car with time budget and non-electric car.

To achieve this, at first you have to create a compound query:

BatchRoutingQueryBuilder.create()
        .withReachableRangeQuery(factory.createReachableRangeQueryForElectric())
        .withReachableRangeQuery(factory.createReachableRangeQueryForCombustion())
        .withReachableRangeQuery(factory.createReachableRangeQueryForElectricLimitTo2Hours())
        .build();

Secondly, pass the created query to the routing api:

Disposable subscribe = getRoutePlannerAPI().planBatchRoute(query)
        .subscribeOn(getWorkingScheduler())
        .observeOn(getResultScheduler())
        .subscribe(
                batchRoutingResponse -> displayRouteAndSetDescription(batchRoutingResponse),
                throwable -> proceedWithError(throwable.getMessage()));

This example shows how Reachable Range calculations for multiple vehicle types and time budgets can be retrieved with a single request to the Batch Routing service.
For each vehicle type, you can see how its type and time budget will affect ranges returned as a result. These ranges are then visualised as polylines on the map.
You can obtain the description of each reachable range by clicking on the polylines.



image

Three possible reachable ranges from Amsterdam by electric car, combustion and electric car with time budget for 2 hours

Matrix routing

Allow your users to send multiple synchronous routing requests with Matrix Routing components. You can calculate a matrix of route summaries for a set of routes defined with origin and destination locations to compare them in an easy way.

Matrix Routing sdk components use Online Matrix Routing API so you can find all details about it in the service documentation.

The set of origins and the set of destinations can be thought of as the column and row headers of a table and each cell in the table contains the costs of routing from the origin to the destination for that cell.
There are generally three types of use cases for Matrix Routing:

  • 1-to-many = from one origin (e.g. your current location) to many destinations (e.g. POIs)

  • many-to-many = from many origins (e.g. taxis) to many destinations (e.g. passengers)

  • many-to-1 = from many origins (e.g. ambulances) to one destination (e.g. patient)

Try out the use cases below in your app.

Sample use case: (One to many) I know a few restaurants and I would like to know to which one I can get to the fastest

1 origin – Amsterdam, 5 restaurants in Amsterdam. The shortest ETA is the active route.


image

One to Many

Sample use case: (Many to many) There are a few taxis and a few passengers to pick up, you would like to compare ETAs for each pairs passengers-taxis to choose the most optimal combination.

2 origins (taxies) and 2 (destinations) passengers. Render all routes for all taxies. The active routes are the ones with the shortest ETA for each pair.


image

Many to Many

Use the code sample below for implementing a similar use case.

To request a matrix query create a MatrixRoutingQuery:

MatrixRoutingQuery query = MatrixRoutingQueryBuilder.create(origins, destinations).build();

and pass it to the routing API:

Disposable subscribe = routePlannerAPI.planMatrixRoutes(query)

The result can be observed with listener or by rx java subscription:

/**
 * The listener for response of the query sent to Matrix Routing online service.
 */
public interface MatrixRoutingResultListener {

    /**
     * Triggered when the response from the matrix routing online service will be available.
     *
     * @param response - The information returned is a container for all route results.
     */
    void onMatrixResult(MatrixRoutingResponse response);

    /**
     * Triggered when the online request for matrix routing failed.
     *
     * @param exception the exception returned when the request to service fails.
     */
    void onMatrixError(ServiceException exception);
}

You can obtain detailed summary of every route in matrix (eg. ETA, delay, distances).