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.createDefaultParametersAsync()
  4. Create Stops and add them to the route task's parameters.
  5. Solve the Route using routeTask.solveRouteAsync(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.cppOfflineRouting.cppOfflineRouting.hOfflineRouting.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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
// [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]

#ifdef PCH_BUILD
#include "pch.hpp"
#endif // PCH_BUILD

#include "OfflineRouting.h"

#include "ArcGISTiledLayer.h"
#include "CompositeSymbol.h"
#include "Envelope.h"
#include "GeometryEngine.h"
#include "Graphic.h"
#include "GraphicsOverlay.h"
#include "Map.h"
#include "MapQuickView.h"
#include "PictureMarkerSymbol.h"
#include "Polyline.h"
#include "RouteParameters.h"
#include "RouteResult.h"
#include "RouteTask.h"
#include "SimpleLineSymbol.h"
#include "SimpleRenderer.h"
#include "Stop.h"
#include "TextSymbol.h"
#include "TileCache.h"
#include "MapTypes.h"
#include "SymbolTypes.h"
#include "Error.h"
#include "GraphicsOverlayListModel.h"
#include "GraphicListModel.h"
#include "RouteTaskInfo.h"
#include "TravelMode.h"
#include "IdentifyGraphicsOverlayResult.h"
#include "Route.h"
#include "Basemap.h"
#include "Point.h"
#include "SpatialReference.h"

#include <QUuid>
#include <memory>
#include <QScopedPointer>
#include <QFileInfo>
#include <QStandardPaths>

using namespace Esri::ArcGISRuntime;

// helper method to get cross platform data path
namespace
{
QString defaultDataPath()
{
  QString dataPath;

#ifdef Q_OS_IOS
  dataPath = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
#else
  dataPath = QStandardPaths::writableLocation(QStandardPaths::HomeLocation);
#endif

  return dataPath;
}
const QUrl pinUrl("qrc:/Samples/Routing/OfflineRouting/orange_symbol.png");
} // namespace

OfflineRouting::OfflineRouting(QObject* parent /* = nullptr */):
  QObject(parent),
  m_pinSymbol(new PictureMarkerSymbol(pinUrl, this)),
  m_stopsOverlay(new GraphicsOverlay(this)),
  m_routeOverlay(new GraphicsOverlay(this))
{
  const QString folderLocation = QString("%1/ArcGIS/Runtime/Data/tpkx/san_diego").arg(defaultDataPath());
  if (!QFileInfo::exists(folderLocation))
  {
    qWarning() << "Please download required data.";
    return;
  }

  const QString fileLocation = folderLocation + QString("/streetmap_SD.tpkx");
  TileCache* tileCache = new TileCache(fileLocation, this);
  ArcGISTiledLayer* tiledLayer = new ArcGISTiledLayer(tileCache, this);
  Basemap* basemap = new Basemap(tiledLayer, this);
  m_map = new Map(basemap, this);
  m_map->setMinScale(100000);

  SimpleLineSymbol* lineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle::Solid, Qt::blue, 2, this);
  SimpleRenderer* routeRenderer = new SimpleRenderer(lineSymbol, this);
  m_routeOverlay->setRenderer(routeRenderer);

  m_pinSymbol->setHeight(50);
  m_pinSymbol->setWidth(50);
  m_pinSymbol->setOffsetY(m_pinSymbol->height() / 2);

  const QString geodatabaseLocation = folderLocation + QString("/sandiego.geodatabase");
  m_routeTask = new RouteTask(geodatabaseLocation, "Streets_ND", this);
  m_routeTask->load();
}

OfflineRouting::~OfflineRouting() = default;

void OfflineRouting::init()
{
  // Register the map view for QML
  qmlRegisterType<MapQuickView>("Esri.Samples", 1, 0, "MapView");
  qmlRegisterType<OfflineRouting>("Esri.Samples", 1, 0, "OfflineRoutingSample");
}

MapQuickView* OfflineRouting::mapView() const
{
  return m_mapView;
}

QStringList OfflineRouting::travelModeNames() const
{
  // if route task not initialized or loaded, then do not execute
  if (!m_routeTask)
    return { };

  if(m_routeTask->loadStatus() != LoadStatus::Loaded)
    return { };

  const QList<TravelMode> modesList = m_routeTask->routeTaskInfo().travelModes();
  QStringList strList;
  for (const TravelMode& mode : modesList)
  {
    strList << mode.name();
  }
  return strList;
}

void OfflineRouting::setTravelModeIndex(int index)
{
  if (m_travelModeIndex == index)
    return;

  m_travelModeIndex = index;
  emit travelModeIndexChanged();
}

int OfflineRouting::travelModeIndex() const
{
  return m_travelModeIndex;
}

void OfflineRouting::connectSignals()
{
  connect(m_routeTask, &RouteTask::doneLoading, this, [this](const Error& loadError)
  {
    if (loadError.isEmpty())
    {
      m_routeTask->createDefaultParametersAsync().then(this, [this](const RouteParameters& defaultParameters)
      {
        m_routeParameters = defaultParameters;
      });
      emit travelModeNamesChanged();
    }
    else
    {
      qDebug() << loadError.message() << loadError.additionalMessage();
    }
  });

  // check whether mouse pressed over an existing stop
  connect(m_mapView, &MapQuickView::mousePressed, this, [this](QMouseEvent& e){
    m_mapView->identifyGraphicsOverlayAsync(m_stopsOverlay, e.position(), 10, false).then(this, [this](IdentifyGraphicsOverlayResult* rawIdentifyResult)
    {
      auto result = std::unique_ptr<IdentifyGraphicsOverlayResult>(rawIdentifyResult);
      if (!result->error().isEmpty())
        qDebug() << result->error().message() << result->error().additionalMessage();

      m_selectedGraphic = nullptr;
      if (!result->graphics().isEmpty())
      {
        // identify selected graphic in m_stopsOverlay
        int index = m_stopsOverlay->graphics()->indexOf(result->graphics().at(0));
        m_selectedGraphic = m_stopsOverlay->graphics()->at(index);
      }
    });
  });

  // get stops from clicked locations
  connect(m_mapView, &MapQuickView::mouseClicked, this, [this](QMouseEvent& e){
    if (!m_selectedGraphic)
    {
      // return if point is outside of bounds
      if (!GeometryEngine::within(m_mapView->screenToLocation(e.position().x(), e.position().y()), m_routableArea))
      {
        qWarning() << "Outside of routable area.";
        return;
      }
      TextSymbol* textSymbol = new TextSymbol(QString::number(m_stopsOverlay->graphics()->size() + 1), Qt::white, 20, HorizontalAlignment::Center, VerticalAlignment::Bottom, this);
      textSymbol->setOffsetY(m_pinSymbol->height() / 2);
      CompositeSymbol* stopLabel = new CompositeSymbol(QList<Symbol*>{m_pinSymbol, textSymbol}, this);
      Graphic* stopGraphic = new Graphic(m_mapView->screenToLocation(e.position().x(), e.position().y()), stopLabel, this);
      m_stopsOverlay->graphics()->append(stopGraphic);
      findRoute();
    }
    e.accept();
  });

  // mouseMoved is processed before identifyGraphicsOverlayCompleted, so must clear graphic upon mouseReleased
  connect(m_mapView, &MapQuickView::mouseReleased, this, [this](QMouseEvent& e) {
    if (m_selectedGraphic)
    {
      m_selectedGraphic = nullptr;
      e.accept();
    }
  });

  // if mouse is moved while pressing on a graphic, the click-and-pan effect of the MapView is prevented by e.accept()
  connect(m_mapView, &MapQuickView::mouseMoved, this, [this](QMouseEvent&e){
    if (m_selectedGraphic)
    {
      e.accept();

      // return if point is outside of bounds
      if (!GeometryEngine::within(m_mapView->screenToLocation(e.position().x(), e.position().y()), m_routableArea))
      {
        qWarning() << "Outside of routable area.";
        return;
      }
      m_selectedGraphic->setGeometry(m_mapView->screenToLocation(e.position().x(), e.position().y()));
      findRoute();
    }
  });
}

void OfflineRouting::findRoute()
{
  if (!m_routeTaskFuture.isFinished() || m_stopsOverlay->graphics()->size() <= 1)
    return;

  QList<Stop> stops;
  for (const Graphic* graphic : *m_stopsOverlay->graphics())
  {
    stops << Stop(geometry_cast<Point>(graphic->geometry()));
  }

  // configure stops and travel mode
  m_routeParameters.setStops(stops);
  m_routeParameters.setTravelMode(m_routeTask->routeTaskInfo().travelModes().at(m_travelModeIndex));

  m_routeTaskFuture = m_routeTask->solveRouteAsync(m_routeParameters);
  m_routeTaskFuture.then(this, [this](const RouteResult& routeResult)
  {
    if (routeResult.isEmpty())
      return;

    // clear old route
    m_routeOverlay->graphics()->clear();
    Polyline routeGeometry = qAsConst(routeResult).routes().first().routeGeometry();
    Graphic* routeGraphic = new Graphic(routeGeometry, this);

    m_routeOverlay->graphics()->append(routeGraphic);
  });
}

// Set the view (created in QML)
void OfflineRouting::setMapView(MapQuickView* mapView)
{
  if (!mapView || mapView == m_mapView)
    return;

  m_mapView = mapView;
  m_mapView->setMap(m_map);

  m_mapView->graphicsOverlays()->append(m_stopsOverlay);
  m_mapView->graphicsOverlays()->append(m_routeOverlay);

  GraphicsOverlay* boundaryOverlay = new GraphicsOverlay(this);
  m_routableArea = Envelope(Point(-13045352.223196, 3864910.900750,SpatialReference::webMercator()), Point(-13024588.857198, 3838880.505604, SpatialReference::webMercator()));
  SimpleLineSymbol* boundarySymbol = new SimpleLineSymbol(SimpleLineSymbolStyle::Dash, Qt::green, 3, this);
  Graphic* boundaryGraphic = new Graphic(m_routableArea, boundarySymbol, this);
  boundaryOverlay->graphics()->append(boundaryGraphic);
  m_mapView->graphicsOverlays()->append(boundaryOverlay);

  connectSignals();

  emit mapViewChanged();
}

void OfflineRouting::resetMap()
{
  m_selectedGraphic = nullptr;
  if (m_stopsOverlay)
    m_stopsOverlay->graphics()->clear();
  if(m_routeOverlay)
    m_routeOverlay->graphics()->clear();
}

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