Navigate route

View inQMLC++
View on GitHub
Sample viewer app

Use a routing service to navigate between points.

screenshot

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

  1. Create a RouteTask using a URL to an online route service.
  2. Generate default RouteParameters using RouteTask.createDefaultParameters().
  3. Set returnStops and returnDirections on the parameters to true.
  4. Add Stops to the parameters for each destination using setStops(stops).
  5. Solve the route using RouteTask.solveRoute(routeParameters) to get a RouteResult.
  6. Create a RouteTracker using the route result, and the index of the desired route to take.
  7. Use trackLocation(Location) to track the location of the device and update the route tracking status.
  8. Use the trackingStatusChanged signal to get the TrackingStatus and 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 a Polyline), or the remaining time, amongst others.
  9. Use the newVoiceGuidance signal to get the VoiceGuidance whenever new instructions are available. From the voice guidance, get the string representing the directions and use a text-to-speech engine to output the maneuver directions.
  10. You can also query the tracking status for the current DirectionManeuver index, retrieve that maneuver from the Route and get its direction text to display in the GUI.
  11. To establish whether the destination has been reached, get the DestinationStatus from the tracking status. If the destination status is Reached, 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

NavigateRoute.cppNavigateRoute.cppNavigateRoute.hNavigateRoute.qml
Use dark colors for code blocksCopy
                                                                                                                                                                                                                                                                                           
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
// [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

#include "NavigateRoute.h"

#include "DirectionManeuverListModel.h"
#include "GeometryEngine.h"
#include "GraphicsOverlay.h"
#include "Location.h"
#include "LocationDisplay.h"
#include "Map.h"
#include "MapQuickView.h"
#include "NavigationTypes.h"
#include "Point.h"
#include "Route.h"
#include "RouteResult.h"
#include "RouteTask.h"
#include "RouteTracker.h"
#include "SimpleMarkerSymbol.h"
#include "SimulatedLocationDataSource.h"
#include "SimulationParameters.h"
#include "Stop.h"
#include "TrackingDistance.h"
#include "TrackingProgress.h"
#include "TrackingStatus.h"
#include "VoiceGuidance.h"

#include <memory>
#include <QList>
#include <QTextToSpeech>
#include <QTime>
#include <QUrl>

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::solveRouteCompleted, this, [this](QUuid, RouteResult routeResult)
  {
    if (routeResult.isEmpty())
      return;

    if (routeResult.routes().empty())
      return;

    m_routeResult = routeResult;
    m_route = qAsConst(m_routeResult).routes()[0];

    // adjust viewpoint to enclose the route with a 100 DPI padding
    m_mapView->setViewpointGeometry(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();
  });

  connect(m_routeTask, &RouteTask::createDefaultParametersCompleted, this, [this](QUuid, 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->solveRoute(defaultParameters);
  });

  connect(m_routeTask, &RouteTask::doneLoading, this, [this](const Error& error)
  {
    if (error.isEmpty())
    {
      m_routeTask->createDefaultParameters();
    }
    else
    {
      qDebug() << error.message() << error.additionalMessage();
    }
  });
}

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->trackLocation(location);
  });

  // 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: " + qAsConst(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)
      {
        m_routeTracker->switchToNextDestination();
      }
      else
      {
        m_simulatedLocationDataSource->stop();
      }
    }
    m_textString = textString;
    emit textStringChanged();
  });

  connect(m_routeTracker, &RouteTracker::trackLocationCompleted, this, [this](QUuid)
  {
    m_routeTracker->generateVoiceGuidance();
  });
}

QString NavigateRoute::textString() const
{
  return m_textString;
}

void NavigateRoute::recenterMap()
{
  m_mapView->locationDisplay()->setAutoPanMode(LocationDisplayAutoPanMode::Navigation);
}

Your browser is no longer supported. Please upgrade your browser for the best experience. See our browser deprecation post for more details.