Use a routing service to navigate between points.

Use case
Navigation is often used by field workers while traveling between points to get live directions based on their location.
How to use the sample
Click ‘Navigate’ to simulate travelling and to receive directions from a preset starting point to a preset destination. Click ‘Recenter’ to recenter the navigation display.
How it works
- Create a
RouteTaskusing a URL to an online route service. - Generate default
RouteParametersusingRouteTask.createDefaultParametersAsync(). - Set
returnStopsandreturnDirectionson the parameters to true. - Add
Stops to the parameters for each destination usingsetStops(stops). - Solve the route using
RouteTask.solveRouteAsync(routeParameters)to get aRouteResult. - Create a
RouteTrackerusing the route result, and the index of the desired route to take. - Use
trackLocationAsync(Location)to track the location of the device and update the route tracking status. - Use the
trackingStatusChangedsignal to get theTrackingStatusand use it to display updated route information. Tracking status includes a variety of information on the route progress, such as the remaining distance, remaining geometry or traversed geometry (represented by aPolyline), or the remaining time, amongst others. - Use the
newVoiceGuidancesignal to get theVoiceGuidancewhenever new instructions are available. From the voice guidance, get thestringrepresenting the directions and use a text-to-speech engine to output the maneuver directions. (NOTE: As of Qt 6.2, QTextToSpeech is not supported). - You can also query the tracking status for the current
DirectionManeuverindex, retrieve that maneuver from theRouteand get its direction text to display in the GUI. - To establish whether the destination has been reached, get the
DestinationStatusfrom the tracking status. If the destination status isReached, we have arrived at the destination and can stop routing. If there are several destinations in your route, and the remaining destination count is greater than 1, switch the route tracker to the next destination.
Relevant API
- DestinationStatus
- DirectionManeuver
- Location
- Route
- RouteParameters
- RouteTask
- RouteTracker
- SimulatedLocationDataSource
- Stop
- VoiceGuidance
About the data
The route taken in this sample interacts with three locations:
- Starts at the San Diego Convention Center, site of the annual Esri User Conference
- Stops at the USS San Diego Memorial
- Ends at the Fleet Science Center, San Diego.
Tags
directions, maneuver, navigation, route, turn-by-turn, voice
Sample Code
// [WriteFile Name=NavigateRoute, Category=Routing]// [Legal]// Copyright 2020 Esri.//// Licensed under the Apache License, Version 2.0 (the "License");// you may not use this file except in compliance with the License.// You may obtain a copy of the License at// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing, software// distributed under the License is distributed on an "AS IS" BASIS,// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.// See the License for the specific language governing permissions and// limitations under the License.// [Legal]
#ifdef PCH_BUILD#include "pch.hpp"#endif // PCH_BUILD
// sample headers#include "NavigateRoute.h"
// ArcGIS Maps SDK headers#include "DirectionManeuver.h"#include "DirectionManeuverListModel.h"#include "Error.h"#include "Graphic.h"#include "GraphicListModel.h"#include "GraphicsOverlay.h"#include "GraphicsOverlayListModel.h"#include "LinearUnit.h"#include "Location.h"#include "LocationDisplay.h"#include "Map.h"#include "MapQuickView.h"#include "MapTypes.h"#include "MapViewTypes.h"#include "NavigationTypes.h"#include "Point.h"#include "Polyline.h"#include "Route.h"#include "RouteParameters.h"#include "RouteResult.h"#include "RouteTask.h"#include "RouteTracker.h"#include "SimpleLineSymbol.h"#include "SimpleMarkerSymbol.h"#include "SimulatedLocationDataSource.h"#include "SimulationParameters.h"#include "SpatialReference.h"#include "Stop.h"#include "SymbolTypes.h"#include "TrackingDistance.h"#include "TrackingProgress.h"#include "TrackingStatus.h"#include "VoiceGuidance.h"
// Qt headers#include <QFuture>#include <QList>#include <QTime>#include <QUrl>#include <QUuid>#include <QtTextToSpeech/QTextToSpeech>
// STL headers#include <memory>
using namespace Esri::ArcGISRuntime;
namespace {const QUrl routeTaskUrl("https://sampleserver6.arcgisonline.com/arcgis/rest/services/NetworkAnalysis/SanDiego/NAServer/Route");const Point conventionCenterPoint(-117.160386727, 32.706608, SpatialReference::wgs84());const Point memorialPoint(-117.173034, 32.712327, SpatialReference::wgs84());const Point aerospaceMuseumPoint(-117.147230, 32.730467, SpatialReference::wgs84());}
NavigateRoute::NavigateRoute(QObject* parent /* = nullptr */): QObject(parent), m_map(new Map(BasemapStyle::ArcGISNavigation, this)){ m_routeOverlay = new GraphicsOverlay(this); m_routeTask = new RouteTask(routeTaskUrl, this); m_speaker = new QTextToSpeech(this);}
NavigateRoute::~NavigateRoute() = default;
void NavigateRoute::init(){ // Register the map view for QML qmlRegisterType<MapQuickView>("Esri.Samples", 1, 0, "MapView"); qmlRegisterType<NavigateRoute>("Esri.Samples", 1, 0, "NavigateRouteSample");}
MapQuickView* NavigateRoute::mapView() const{ return m_mapView;}
// Set the view (created in QML)void NavigateRoute::setMapView(MapQuickView* mapView){ if (!mapView || mapView == m_mapView) return;
m_mapView = mapView; m_mapView->setMap(m_map);
m_mapView->graphicsOverlays()->append(m_routeOverlay); connectRouteTaskSignals();
m_routeTask->load();
// add graphics for the predefined stops SimpleMarkerSymbol* stopSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle::Diamond, Qt::red, 20, this); m_routeOverlay->graphics()->append(new Graphic(conventionCenterPoint, stopSymbol, this)); m_routeOverlay->graphics()->append(new Graphic(memorialPoint, stopSymbol, this)); m_routeOverlay->graphics()->append(new Graphic(aerospaceMuseumPoint, stopSymbol, this));
emit mapViewChanged();}
void NavigateRoute::connectRouteTaskSignals(){ connect(m_routeTask, &RouteTask::doneLoading, this, [this](const Error& error) { if (!error.isEmpty()) { qDebug() << error.message() << error.additionalMessage(); return; } m_routeTask->createDefaultParametersAsync().then(this, [this](RouteParameters defaultParameters) { // set values for parameters defaultParameters.setReturnStops(true); defaultParameters.setReturnDirections(true); defaultParameters.setReturnRoutes(true); defaultParameters.setOutputSpatialReference(SpatialReference::wgs84());
Stop stop1(conventionCenterPoint); Stop stop2(memorialPoint); Stop stop3(aerospaceMuseumPoint);
QList<Stop> stopsList = {stop1, stop2, stop3}; defaultParameters.setStops(stopsList);
m_routeTask->solveRouteAsync(defaultParameters).then(this, [this](const RouteResult& routeResult) { if (routeResult.isEmpty()) return;
if (routeResult.routes().empty()) return;
m_routeResult = routeResult; m_route = std::as_const(m_routeResult).routes()[0];
// adjust viewpoint to enclose the route with a 100 DPI padding m_mapView->setViewpointGeometryAsync(m_route.routeGeometry(), 100);
// create a graphic to show the route m_routeAheadGraphic = new Graphic(m_route.routeGeometry(), new SimpleLineSymbol(SimpleLineSymbolStyle::Dash, Qt::blue, 5, this), this);
// create a graphic to represent the route that's been traveled (initially empty). m_routeTraveledGraphic = new Graphic(Geometry(), new SimpleLineSymbol(SimpleLineSymbolStyle::Solid, Qt::cyan, 3, this), this); m_routeOverlay->graphics()->append(m_routeAheadGraphic); m_routeOverlay->graphics()->append(m_routeTraveledGraphic);
m_navigationEnabled = true; emit navigationEnabledChanged(); }); }); });}
bool NavigateRoute::navigationEnabled() const{ return m_navigationEnabled;}
bool NavigateRoute::recenterEnabled() const{ return m_recenterEnabled;}
void NavigateRoute::startNavigation(){ // disable the navigation button m_navigationEnabled = false; emit navigationEnabledChanged();
// get the directions for the route m_directions = m_route.directionManeuvers(this);
// create a route tracker m_routeTracker = new RouteTracker(m_routeResult, 0, this); connectRouteTrackerSignals();
// enable the RouteTracker to know when the QTextToSpeech engine is ready m_routeTracker->setSpeechEngineReadyFunction([speaker = m_speaker]() -> bool { return speaker->state() == QTextToSpeech::State::Ready; });
// enable "recenter" button when location display is moved from nagivation mode connect(m_mapView->locationDisplay(), &LocationDisplay::autoPanModeChanged, this, [this](LocationDisplayAutoPanMode autoPanMode) { m_recenterEnabled = autoPanMode != LocationDisplayAutoPanMode::Navigation; emit recenterEnabledChanged(); });
connect(m_mapView->locationDisplay(), &LocationDisplay::locationChanged, this, [this](const Location& location) { m_routeTracker->trackLocationAsync(location).then(this, [this]() { m_routeTracker->generateVoiceGuidance(); }); });
// turn on map view's navigation mode m_mapView->locationDisplay()->setAutoPanMode(LocationDisplayAutoPanMode::Navigation);
// add a data source for the location display SimulationParameters* simulationParameters = new SimulationParameters(QDateTime::currentDateTime(), 40.0, 0.0, 0.0, this); // set speed m_simulatedLocationDataSource = new SimulatedLocationDataSource(this); m_simulatedLocationDataSource->setLocationsWithPolyline(m_route.routeGeometry(), simulationParameters); m_mapView->locationDisplay()->setDataSource(m_simulatedLocationDataSource); m_simulatedLocationDataSource->start();}
void NavigateRoute::connectRouteTrackerSignals(){ connect(m_routeTracker, &RouteTracker::newVoiceGuidance, this, [this](VoiceGuidance* rawVoiceGuidance) { auto voiceGuidance = std::unique_ptr<VoiceGuidance>(rawVoiceGuidance); m_speaker->say(voiceGuidance->text()); });
connect(m_routeTracker, &RouteTracker::trackingStatusChanged, this, [this](TrackingStatus* rawTrackingStatus) { auto trackingStatus = std::unique_ptr<TrackingStatus>(rawTrackingStatus); QString textString("Route status: \n"); if (trackingStatus->destinationStatus() == DestinationStatus::NotReached || trackingStatus->destinationStatus() == DestinationStatus::Approaching) { textString += "Distance remaining: " + trackingStatus->routeProgress()->remainingDistance()->displayText() + " " + trackingStatus->routeProgress()->remainingDistance()->displayTextUnits().pluralDisplayName() + "\n"; QTime time = QTime::fromMSecsSinceStartOfDay(trackingStatus->routeProgress()->remainingTime() * 60 * 1000); // convert time to milliseconds textString += "Time remaining: " + time.toString("hh:mm:ss") + "\n";
// display next direction if (DirectionManeuverListModel* directionList = dynamic_cast<DirectionManeuverListModel*>(m_directions)) { if (trackingStatus->currentManeuverIndex() + 1 < directionList->directionManeuvers().length()) { textString += "Next direction: " + std::as_const(directionList)->directionManeuvers()[trackingStatus->currentManeuverIndex() + 1].directionText() + "\n"; } } m_routeTraveledGraphic->setGeometry(trackingStatus->routeProgress()->traversedGeometry()); m_routeAheadGraphic->setGeometry(trackingStatus->routeProgress()->remainingGeometry()); } else if (trackingStatus->destinationStatus() == DestinationStatus::Reached) { textString += "Destination reached.\n";
// set the route geometries to reflect the completed route m_routeAheadGraphic->setGeometry(Geometry()); m_routeTraveledGraphic->setGeometry(trackingStatus->routeResult().routes()[0].routeGeometry());
// navigate to next stop, if available if (trackingStatus->remainingDestinationCount() > 1) { auto future = m_routeTracker->switchToNextDestinationAsync(); Q_UNUSED(future); } else { m_simulatedLocationDataSource->stop(); } } m_textString = textString; emit textStringChanged(); });}
QString NavigateRoute::textString() const{ return m_textString;}
void NavigateRoute::recenterMap(){ m_mapView->locationDisplay()->setAutoPanMode(LocationDisplayAutoPanMode::Navigation);}// [WriteFile Name=NavigateRoute, Category=Routing]// [Legal]// Copyright 2020 Esri.//// Licensed under the Apache License, Version 2.0 (the "License");// you may not use this file except in compliance with the License.// You may obtain a copy of the License at// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing, software// distributed under the License is distributed on an "AS IS" BASIS,// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.// See the License for the specific language governing permissions and// limitations under the License.// [Legal]
#ifndef NAVIGATEROUTE_H#define NAVIGATEROUTE_H
// ArcGIS Maps SDK headers#include "Route.h"#include "RouteResult.h"
// Qt headers#include <QObject>#include <QString>
namespace Esri::ArcGISRuntime{class Graphic;class GraphicsOverlay;class Map;class MapQuickView;class RouteTask;class RouteTracker;class SimulatedLocationDataSource;}
class QTextToSpeech;
class QAbstractListModel;
Q_MOC_INCLUDE("MapQuickView.h")Q_MOC_INCLUDE("QAbstractListModel")
class NavigateRoute : public QObject{ Q_OBJECT
Q_PROPERTY(Esri::ArcGISRuntime::MapQuickView* mapView READ mapView WRITE setMapView NOTIFY mapViewChanged) Q_PROPERTY(bool navigationEnabled READ navigationEnabled NOTIFY navigationEnabledChanged) Q_PROPERTY(bool recenterEnabled READ recenterEnabled NOTIFY recenterEnabledChanged) Q_PROPERTY(QString textString READ textString NOTIFY textStringChanged)
public: explicit NavigateRoute(QObject* parent = nullptr); ~NavigateRoute();
static void init();
Q_INVOKABLE void startNavigation(); Q_INVOKABLE void recenterMap();
signals: void mapViewChanged(); void navigationEnabledChanged(); void recenterEnabledChanged(); void textStringChanged();
private: Esri::ArcGISRuntime::MapQuickView* mapView() const; void setMapView(Esri::ArcGISRuntime::MapQuickView* mapView); bool navigationEnabled() const; bool recenterEnabled() const; QString textString() const; void connectRouteTaskSignals(); void connectRouteTrackerSignals();
Esri::ArcGISRuntime::Graphic* m_routeAheadGraphic = nullptr; Esri::ArcGISRuntime::Graphic* m_routeTraveledGraphic = nullptr; Esri::ArcGISRuntime::GraphicsOverlay* m_routeOverlay = nullptr; Esri::ArcGISRuntime::Map* m_map = nullptr; Esri::ArcGISRuntime::MapQuickView* m_mapView = nullptr; Esri::ArcGISRuntime::RouteTask* m_routeTask = nullptr; Esri::ArcGISRuntime::Route m_route; Esri::ArcGISRuntime::RouteResult m_routeResult; Esri::ArcGISRuntime::RouteTracker* m_routeTracker = nullptr; Esri::ArcGISRuntime::SimulatedLocationDataSource* m_simulatedLocationDataSource = nullptr; QAbstractListModel* m_directions = nullptr; bool m_navigationEnabled = false; bool m_recenterEnabled = false; QString m_textString = ""; QTextToSpeech* m_speaker = nullptr;};
#endif // NAVIGATEROUTE_H// [WriteFile Name=NavigateRoute, Category=Routing]// [Legal]// Copyright 2020 Esri.//// Licensed under the Apache License, Version 2.0 (the "License");// you may not use this file except in compliance with the License.// You may obtain a copy of the License at// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing, software// distributed under the License is distributed on an "AS IS" BASIS,// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.// See the License for the specific language governing permissions and// limitations under the License.// [Legal]
import QtQuickimport QtQuick.Controlsimport Esri.Samplesimport QtQuick.Layouts
Item {
// add a mapView component MapView { id: view anchors.fill: parent
Component.onCompleted: { // Set the focus on MapView to initially enable keyboard navigation forceActiveFocus(); }
Rectangle { id: backBox z: 1 width: buttonRow.width * 1.5 height: 200 color: "#FBFBFB" border.color: "black" anchors.top: parent.top anchors.left: parent.left anchors.margins: 20
RowLayout { id: buttonRow anchors { top: parent.top horizontalCenter: parent.horizontalCenter margins: 5 } Button { text: "Navigate" enabled: model.navigationEnabled onClicked: { model.startNavigation(); } } Button { text: "Recenter" enabled: model.recenterEnabled onClicked: { model.recenterMap(); } } }
Rectangle { anchors { top: buttonRow.bottom left: parent.left margins: 5 } width: parent.width Text { padding: 5 width: parent.width wrapMode: Text.Wrap text: model.textString } } } }
// Declare the C++ instance which creates the map etc. and supply the view NavigateRouteSample { id: model mapView: view }}// [Legal]// Copyright 2020 Esri.//// Licensed under the Apache License, Version 2.0 (the "License");// you may not use this file except in compliance with the License.// You may obtain a copy of the License at// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing, software// distributed under the License is distributed on an "AS IS" BASIS,// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.// See the License for the specific language governing permissions and// limitations under the License.// [Legal]
// sample headers#include "NavigateRoute.h"
// ArcGIS Maps SDK headers#include "ArcGISRuntimeEnvironment.h"
// Qt headers#include <QDir>#include <QGuiApplication>#include <QQmlApplicationEngine>
// Platform specific headers#ifdef Q_OS_WIN#include <Windows.h>#endif
int main(int argc, char *argv[]){ Esri::ArcGISRuntime::ArcGISRuntimeEnvironment::setUseLegacyAuthentication(false); QGuiApplication app(argc, argv); app.setApplicationName(QString("NavigateRoute"));
// Use of ArcGIS location services, such as basemap styles, geocoding, and routing services, // requires an access token. For more information see // https://links.esri.com/arcgis-runtime-security-auth.
// The following methods grant an access token:
// 1. User authentication: Grants a temporary access token associated with a user's ArcGIS account. // To generate a token, a user logs in to the app with an ArcGIS account that is part of an // organization in ArcGIS Online or ArcGIS Enterprise.
// 2. API key authentication: Get a long-lived access token that gives your application access to // ArcGIS location services. Go to the tutorial at https://links.esri.com/create-an-api-key. // Copy the API Key access token.
const QString accessToken = QString("");
if (accessToken.isEmpty()) { qWarning() << "Use of ArcGIS location services, such as the basemap styles service, requires" << "you to authenticate with an ArcGIS account or set the API Key property."; } else { Esri::ArcGISRuntime::ArcGISRuntimeEnvironment::setApiKey(accessToken); }
// Initialize the sample NavigateRoute::init();
// Initialize application view QQmlApplicationEngine engine; // Add the import Path engine.addImportPath(QDir(QCoreApplication::applicationDirPath()).filePath("qml"));
#ifdef ARCGIS_RUNTIME_IMPORT_PATH_2 engine.addImportPath(ARCGIS_RUNTIME_IMPORT_PATH_2);#endif
// Set the source engine.load(QUrl("qrc:/Samples/Routing/NavigateRoute/main.qml"));
return app.exec();}// Copyright 2020 Esri.
// Licensed under the Apache License, Version 2.0 (the "License");// you may not use this file except in compliance with the License.// You may obtain a copy of the License at// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software// distributed under the License is distributed on an "AS IS" BASIS,// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.// See the License for the specific language governing permissions and// limitations under the License.
import QtQuick.Controlsimport Esri.Samples
ApplicationWindow { visible: true width: 800 height: 600
NavigateRoute { anchors.fill: parent }}