Navigate route

View inC++QMLView on GitHubSample 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 trackRuntimeLocation(Location) to track the location of the device and update the route tracking status.
  8. Use the trackingStatusResultChanged 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 newVoiceGuidanceResultChanged 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 Enums.DestinationStatusReached, 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.qmlNavigateRoute.qmlNavigateRouteSpeaker.cppNavigateRouteSpeaker.h
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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
// [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 QtQuick
import QtQuick.Controls
import QtQuick.Layouts
import QtPositioning
import Esri.ArcGISRuntime
import Esri.samples

Rectangle {
    id: rootRectangle
    clip: true
    width: 800
    height: 600

    readonly property url routeTaskUrl: "https://sampleserver6.arcgisonline.com/arcgis/rest/services/NetworkAnalysis/SanDiego/NAServer/Route"
    property var m_route: null
    property var m_routeResult: null
    property var directionListModel: null
    property string textString: ""

    MapView {
        id: mapView
        anchors.fill: parent

        Component.onCompleted: {
            // Set the focus on MapView to initially enable keyboard navigation
            forceActiveFocus();
        }

        Map {
            Basemap {
                initStyle: Enums.BasemapStyleArcGISNavigation
            }
        }

        GraphicsOverlay {
            id: routeOverlay
            Graphic {
                id: routeAheadGraphic
                SimpleLineSymbol {
                    style: Enums.SimpleLineSymbolStyleDash
                    color: "blue"
                    width: 5
                }
            }
            Graphic {
                id: routeTraveledGraphic
                SimpleLineSymbol {
                    style: Enums.SimpleLineSymbolStyleSolid
                    color: "cyan"
                    width: 3
                }
            }
            Graphic {
                Point {
                    id: conventionCenterPoint
                    x: -117.160386727
                    y: 32.706608
                    SpatialReference {wkid: 4326}
                }
                symbol: stopSymbol
            }
            Graphic {
                Point {
                    id: memorialPoint
                    x: -117.173034
                    y: 32.712327
                    SpatialReference {wkid: 4326}
                }
                symbol: stopSymbol
            }
            Graphic {
                Point {
                    id: aerospaceMuseumPoint
                    x: -117.147230
                    y: 32.730467
                    SpatialReference {wkid: 4326}
                }
                symbol: stopSymbol
            }
        }

        SimpleMarkerSymbol {
            id: stopSymbol
            style: Enums.SimpleMarkerSymbolStyleDiamond
            color: "red"
            size: 20
        }

        Stop {
            id: stop1
            geometry: conventionCenterPoint
        }
        Stop {
            id: stop2
            geometry: memorialPoint
        }
        Stop {
            id: stop3
            geometry: aerospaceMuseumPoint
        }

        RouteTask {
            id: routeTask
            url: routeTaskUrl
            Component.onCompleted: {
                load();
            }
            onLoadStatusChanged: {
                if (loadStatus === Enums.LoadStatusLoaded) {
                    createDefaultParameters();
                }
            }
            onCreateDefaultParametersStatusChanged: {
                if (createDefaultParametersStatus !== Enums.TaskStatusCompleted) {
                    return;
                }

                createDefaultParametersResult.returnStops = true;
                createDefaultParametersResult.returnDirections = true;
                createDefaultParametersResult.returnRoutes = true;
                createDefaultParametersResult.outputSpatialReference = Factory.SpatialReference.createWgs84();
                createDefaultParametersResult.setStops([stop1, stop2, stop3]);

                // solve the route with these parameters
                routeTask.solveRoute(createDefaultParametersResult);
            }
            onSolveRouteStatusChanged: {
                if (solveRouteStatus === Enums.TaskStatusCompleted) {
                    if (solveRouteResult.routes.length > 0) {
                        m_routeResult = solveRouteResult;
                        m_route = solveRouteResult.routes[0];
                        mapView.setViewpointGeometryAndPadding(m_route.routeGeometry, 100);
                        routeAheadGraphic.geometry = m_route.routeGeometry;
                        navigateButton.enabled = true;
                    }
                }
            }
        }

        locationDisplay.onLocationChanged: {
            routeTracker.trackRuntimeLocation(locationDisplay.location);
        }

        // enable "recenter" button
        locationDisplay.onAutoPanModeChanged: {
            recenterButton.enabled = locationDisplay.autoPanMode !== Enums.LocationDisplayAutoPanModeNavigation;
        }

        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 {
                    id: navigateButton
                    text: "Navigate"
                    enabled: false
                    onClicked: {
                        startNavigation();
                        enabled = false;
                    }

                }
                Button {
                    id: recenterButton
                    text: "Recenter"
                    enabled: false
                    onClicked: {
                        recenterMap();
                    }
                }
            }

            Rectangle {
                anchors {
                    top: buttonRow.bottom
                    left: parent.left
                    margins: 5
                }
                width: parent.width
                Text {
                    padding: 5
                    width: parent.width
                    wrapMode: Text.Wrap
                    text: textString
                }
            }
        }

        SimulatedLocationDataSource {
            id: simulatedLocationDataSource
        }

        SimulationParameters {
            id: simulationParameters
            velocity: 40
        }

        RouteTracker {
            id: routeTracker

            onTrackingStatusResultChanged: {
                textString = "Route status: \n";
                if (routeTracker.trackingStatusResult.destinationStatus === Enums.DestinationStatusApproaching || routeTracker.trackingStatusResult.destinationStatus === Enums.DestinationStatusNotReached) {
                    textString += "Distance remaining: " + trackingStatusResult.routeProgress.remainingDistance.displayText + " " +
                            trackingStatusResult.routeProgress.remainingDistance.displayTextUnits.pluralDisplayName + "\n";
                    const time = new Date(trackingStatusResult.routeProgress.remainingTime * 60 * 1000);
                    const hours = time.getUTCHours();
                    const minutes = time.getUTCMinutes();
                    const seconds = time.getSeconds();
                    textString += "Time remaining: " + hours.toString().padStart(2, '0') + ':' + minutes.toString().padStart(2, '0') + ':' +
                            seconds.toString().padStart(2, '0') + "\n";

                    // display next direction
                    if (trackingStatusResult.currentManeuverIndex + 1 < directionListModel.count) {
                        textString += "Next direction: " + directionListModel.get(trackingStatusResult.currentManeuverIndex + 1).directionText;
                    }

                    routeTraveledGraphic.geometry = trackingStatusResult.routeProgress.traversedGeometry;
                    routeAheadGraphic.geometry = trackingStatusResult.routeProgress.remainingGeometry;
                } else if (routeTracker.trackingStatusResult.destinationStatus === Enums.DestinationStatusReached) {
                    textString += "Destination reached.\n";

                    // set the route geometries to reflect the completed route
                    routeTraveledGraphic.geometry = trackingStatusResult.routeResult.routes[0].routeGeometry;

                    // navigate to next stop, if available
                    if (trackingStatusResult.remainingDestinationCount > 1) {
                        switchToNextDestination();
                    } else {
                        simulatedLocationDataSource.stop();
                    }
                }
            }

            // output new voice guidance
            onNewVoiceGuidanceResultChanged: {
                speaker.textToSpeech(newVoiceGuidanceResult.text);
            }

            // set a callback to indicate if the speech engine is ready to speak
            speechEngineReadyCallback: function() {
                return speaker.textToSpeechEngineReady();
            }
        }
    }

    NavigateRouteSpeaker {
        id: speaker
    }

    function startNavigation() {
        // get the directions for the route
        directionListModel = m_route.directionManeuvers;

        // set properties for route tracker
        routeTracker.routeResult = m_routeResult;
        routeTracker.routeIndex = 0;

        // turn on mapview's navigation mode
        mapView.locationDisplay.autoPanMode = Enums.LocationDisplayAutoPanModeNavigation;

        // add a data source for the location display
        simulatedLocationDataSource.setLocationsWithPolylineAndParameters(m_route.routeGeometry, simulationParameters);
        mapView.locationDisplay.dataSource = simulatedLocationDataSource;
        simulatedLocationDataSource.start();
    }

    function recenterMap() {
        mapView.locationDisplay.autoPanMode = Enums.LocationDisplayAutoPanModeNavigation;
    }
}

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