Offline routing

View inC++QMLView on GitHubSample viewer app

This sample demonstrates how to solve a route on-the-fly using offline data.

screenshot

Use case

You can use an offline network to enable routing in disconnected scenarios. For example, you could provide offline location capabilities to field workers repairing critical infrastructure in a disaster when network availability is limited.

How to use the sample

Click near a road to start adding a stop to the route, click again to place it on the map. A number graphic will show its order in the route. After adding at least 2 stops, a route will display. Choose "Fastest" or "Shortest" to control how the route is optimized. To move a stop, click on the graphic, and while continuing to press on the graphic, move the mouse to reposition. Release the mouse to set the new position. The route will update on-the-fly while moving stops. The green box marks the boundary of the route geodatabase.

How it works

To display a Route using a RouteTask with offline data:

  1. Create the map's Basemap from a local tile package using a TileCache and ArcGISTiledLayer
  2. Create a RouteTask with an offline locator geodatabase
  3. Get the RouteParameters using routeTask.createDefaultParameters()
  4. Create Stops and add them to the route task's parameters.
  5. Solve the Route using routeTask.solveRoute(routeParameters)
  6. Create a graphic with the route's geometry and a SimpleLineSymbol and display it on another GraphicsOverlay.

Relevant API

  • RouteParameters
  • RouteResult
  • RouteTask
  • Stop
  • TravelMode

Offline data

The data used by this sample is available on ArcGIS Online.

Link Local Location
San Diego Streets TPKX <userhome>/ArcGIS/Runtime/Data/tpkx/san_diego

About the data

This sample uses a pre-packaged sample dataset consisting of a geodatabase with a San Diego road network and a tile package with a streets basemap.

Tags

connectivity, disconnected, fastest, locator, navigation, network analysis, offline, routing, shortest, turn-by-turn

Sample Code

OfflineRouting.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
// [WriteFile Name=OfflineRouting, 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 Esri.ArcGISRuntime
import Esri.ArcGISExtras
import QtQml
import QtQuick.Layouts

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

    readonly property url dataPath: {
        Qt.platform.os === "ios" ?
                    System.writableLocationUrl(System.StandardPathsDocumentsLocation) + "/ArcGIS/Runtime/Data/tpkx/" :
                    System.writableLocationUrl(System.StandardPathsHomeLocation) + "/ArcGIS/Runtime/Data/tpkx/"
    }
    readonly property url pinUrl: "qrc:/Samples/Routing/OfflineRouting/orange_symbol.png"
    property var findRoute;
    property Graphic selectedGraphic: null;

    MapView {
        id: mapView
        anchors.fill: parent

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

        RowLayout {
            anchors {
                left: parent.left
                top: parent.top
            }
            ComboBox {
                id: comboBox
                Layout.fillWidth: true
                onCurrentIndexChanged: {
                    routeTask.findRoute();
                }

                // Add a background to the ComboBox
                Rectangle {
                    anchors.fill: parent
                    radius: 10
                    // Make the rectangle visible if a dropdown indicator exists
                    // An indicator only exists if a theme is set
                    visible: parent.indicator
                    border.width: 1
                }
            }
            Button {
                text: "Reset"
                Layout.fillWidth: true
                onClicked: {
                    stopsOverlay.graphics.clear();
                    routeOverlay.graphics.clear();
                    selectedGraphic = null;
                }
            }
        }

        Map {
            minScale: 100000
            Basemap {
                ArcGISTiledLayer {
                    TileCache {
                        path: dataPath + "san_diego/streetmap_SD.tpkx"
                    }
                }
            }
        }

        GraphicsOverlay {
            id: stopsOverlay
        }

        GraphicsOverlay {
            id: routeOverlay
            renderer: SimpleRenderer {
                SimpleLineSymbol {
                    style: Enums.SimpleLineSymbolStyleSolid
                    color: "blue"
                    width: 2
                }
            }
        }

        PictureMarkerSymbol {
            id: pinSymbol
            url: pinUrl
            height: 50
            width: 50
            offsetY: height/2
        }

        GraphicsOverlay {
            id: boundaryOverlay
            Graphic {
                Envelope {
                    id: routableArea
                    xMin: -13045352.223196
                    xMax: -13024588.857198
                    yMin: 3864910.900750
                    yMax: 3838880.505604
                    SpatialReference {wkid: 3857}
                }
                SimpleLineSymbol {
                    style: Enums.SimpleLineSymbolStyleDash
                    color: "lime"
                    width: 3
                }
            }
        }

        RouteTask {
            id: routeTask
            url: dataPath + "san_diego/sandiego.geodatabase"
            networkName: "Streets_ND"

            onComponentCompleted: {
                load();
            }

            onLoadStatusChanged: {
                if (loadStatus === Enums.LoadStatusLoaded) {
                    // assign ComboBox model from travel mode names
                    const modesList = routeTask.routeTaskInfo.travelModes;
                    const travelModeNames = [];
                    for (let i = 0; i < modesList.length; i++) {
                        travelModeNames.push(modesList[i].name);
                    }
                    comboBox.model = travelModeNames;
                    createDefaultParameters();
                }
            }

            function findRoute() {
                if (routeTask.solveRouteStatus === Enums.TaskStatusInProgress)
                    return;

                if (createDefaultParametersResult === null)
                    return;

                const routeParameters = createDefaultParametersResult;
                const stopsList = [];
                const numGraphics = stopsOverlay.graphics.count;
                if (numGraphics > 1) {
                    for (let i = 0; i < numGraphics; i++) {
                        const tempStop = ArcGISRuntimeEnvironment.createObject("Stop", {geometry: stopsOverlay.graphics.get(i).geometry});
                        stopsList.push(tempStop);
                    }
                    routeParameters.setStops(stopsList);
                    routeParameters.travelMode = routeTask.routeTaskInfo.travelModes[comboBox.currentIndex];

                    routeTask.solveRoute(routeParameters);
                }
            }

            onErrorChanged: {
                console.log(routeTask.error.message, routeTask.error.additionalMessage);
            }

            onSolveRouteStatusChanged: {
                if (solveRouteStatus === Enums.TaskStatusCompleted) {
                    // clear old route
                    routeOverlay.graphics.clear();
                    if (routeTask.error) {
                        console.warn(routeTask.error.message);
                    }
                    const routeGraphic = ArcGISRuntimeEnvironment.createObject("Graphic", {geometry: solveRouteResult.routes[0].routeGeometry});
                    routeOverlay.graphics.append(routeGraphic);
                }
            }
        }

        onIdentifyGraphicsOverlayStatusChanged: {
            if (identifyGraphicsOverlayStatus !== Enums.TaskStatusCompleted)
                return;

            if (identifyGraphicsOverlayResult === null) {
                return;
            }

            if (identifyGraphicsOverlayResult.graphics.length === 0) {
                selectedGraphic = null;
            } else {
                const index = stopsOverlay.graphics.indexOf(identifyGraphicsOverlayResult.graphics[0]);
                selectedGraphic = stopsOverlay.graphics.get(index);
            }
        }

        // check whether mouse pressed over an existing stop
        onMousePressed: mouse => {
            mapView.identifyGraphicsOverlay(stopsOverlay, mouse.x, mouse.y, 10, false);
        }

        // get stops from clicked locations and find route
        onMouseClicked: mouse => {
            if (!selectedGraphic) {
                const clickedPoint = mapView.screenToLocation(mouse.x, mouse.y);
                if (!GeometryEngine.within(clickedPoint, routableArea)) {
                    console.warn("Outside of routable area");
                    return;
                }
                const textSymbol = ArcGISRuntimeEnvironment.createObject("TextSymbol", {color: "white",
                                                                            horizontalAlignment: Enums.HorizontalAlignmentCenter,
                                                                            verticalAlignment: Enums.VerticalAlignmentBottom,
                                                                            size: 20, text: stopsOverlay.graphics.count + 1});
                textSymbol.offsetY = pinSymbol.height/2;
                const stopSymbol = ArcGISRuntimeEnvironment.createObject("CompositeSymbol");
                stopSymbol.symbols.append(pinSymbol);
                stopSymbol.symbols.append(textSymbol);

                const stopGraphic = ArcGISRuntimeEnvironment.createObject("Graphic", {geometry: clickedPoint, symbol: stopSymbol});
                stopsOverlay.graphics.append(stopGraphic);
                routeTask.findRoute();
            }
            mouse.accepted = true;
        }

        // if mouse is moved while pressing on a graphic, the click-and-pan effect of the MapView is prevented by mouse.accepted = true
        // and the mouse position is tracked and route is updated on-the-fly
        onMousePositionChanged: mouse => {
            mouse.accepted = !!selectedGraphic; // whether to pass mouse event to MapView
            if (selectedGraphic) {
                if (!GeometryEngine.within(mapView.screenToLocation(mouse.x, mouse.y), routableArea)) {
                    console.warn("Outside of routable area");
                    return;
                }
                selectedGraphic.geometry = mapView.screenToLocation(mouse.x, mouse.y);
                routeTask.findRoute();
            }
        }

        // mouseMoved is processed before identifyGraphicsOverlayCompleted, so must clear graphic upon mouseReleased
        onMouseReleased: mouse => {
            if (selectedGraphic) {
                selectedGraphic = null;
                mouse.accepted = true;
            }
        }
    }

    BusyIndicator {
        anchors.centerIn: parent
        visible: true
        running: routeTask.taskStatus === Enums.TaskStatusInProgress
    }
}

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