Skip to content

Calculate Route

Calculate a route and show it on map.

Calculate Route

Use case

Calculate a route between two given pairs of coordinates then display it on map.

How to use the sample

First, get an API key token, see the Getting Started guide.

Download the Maps & Navigation SDK for C++ archive file for Linux or Windows

When you open the sample, you’ll be viewing the scene from above. A fly will be performed to the calculated route.

How it works

  1. Create an instance of Environment and set your API key token:

1Environment& env = Environment::GetInstance();
4// Project API token available at:
7std::string projectApiToken = ""; //YOUR_TOKEN
  1. The SDK is initialized with your API key token string and the log file path, where to write the application logs. Note that logFilePath is not initialized by default, which means that no logs are written. The logFilePath is initialized with the first command line argument, if any.

1std::string logFilePath;
2if ( argc > 1 )
3   logFilePath = std::string(argv[1]);
5env.InitSDK( projectApiToken, logFilePath.c_str() );
  1. Create a MapViewListener, OpenGLContext and MapView.

1MapViewListenerImpl listener;
2auto oglContext = env.ProduceOpenGLContext("calculateRoute");
3gem::StrongPointer<gem::MapView> mapView = gem::MapView::produce(oglContext, &listener);
  1. Create a RouteList, a ProgressListener, a LandmarkList with two Landmarks in it and a RoutePreferences object.

1gem::RouteList routes;
3    ProgressListener calculateRouteListener;
4    gem::LandmarkList waypoints;
5    waypoints.push_back(gem::Landmark("San Francisco", { 37.77903, -122.41991 }));
6    waypoints.push_back(gem::Landmark("San Jose", { 37.33619, -121.89058 }));
7    gem::RoutePreferences preferences;
  1. Call the RoutingService using RouteList, LandmarkList, RoutePreferences and the progress listener. Wait up to 15 seconds (15000 milliseconds) for the route computation to complete.

1    gem::RoutingService().calculateRoute(routes, waypoints, preferences, &calculateRouteListener);
2    auto ret = WAIT_UNTIL(std::bind(&ProgressListener::IsFinished, &calculateRouteListener), 15000);
  1. Once the route calculation operation completes, if the resulting route list contains at least one route, add the first calculated route (at index 0) to the MapViewPreferences routes collection. Instruct the MapView to center on the first route with a 2 second animation.

1if (routes.size() > 0)
3    mapView->preferences().routes().add(routes[0], true);
4    mapView->centerOnRoute(routes[0], gem::Rect(), gem::Animation(gem::AnimationLinear, gem::ProgressListener(), 2000));
5    auto ret = WAIT_UNTIL(std::bind(&MapViewListenerImpl::IsFinished, &listener), 15000);

C++ Examples

Maps SDK for C++ Examples can be downloaded or cloned with Git