Find closest facility to an incident (interactive)

View on GitHubSample viewer app

Find a route to the closest facility from a location.

screenshot

Use case

Quickly and accurately determining the most efficient route between a location and a facility is a frequently encountered task. For example, a paramedic may need to know which hospital in the vicinity offers the possibility of getting an ambulance patient critical medical care in the shortest amount of time. Solving for the closest hospital to the ambulance's location using an impedance of "travel time" would provide this information.

How to use the sample

Click near any of the hospitals and a route will be displayed from that clicked location to the nearest hospital.

How it works

  1. Create a ClosestFacilityTask using an Url from an online service.
  2. Get a ClosestFacilityParameters from this task, using createDefaultParametersAsync.
  3. Add a list of facilities to the task parameters, using ClosestFacilityParameters::setFacilities(const QList<Facility>& facilities);.
  4. Add an incident to the parameters, using ClosestFacilityParameters::setIncidents(const QList<Incident>& incidents);.
  5. Get the ClosestFacilityResult from solving the task with parameters: , ClosestFacilityTask::solveClosestFacilityAsync(const ClosestFacilityParameters& closestFacilityParameters);.
  6. Get the ranked list of the indices of the closest facilities to the incident, ClosestFacilityResult::rankedFacilities(int incidentIndex) const;.
  7. Get the index of the closest facility (e.g. the first index in the ranked list).
  8. Find the closest facility route, ClosestFacilityResult::route(int facilityIndex, int incidentIndex) const;.
  9. Display the route on the MapView:
  • create a Graphic from the route geometry, new Graphic(route.routeGeometry(), this).
  • add graphic to GraphicsOverlay which is attached to the mapview.

Relevant API

  • ClosestFacilityParameters
  • ClosestFacilityResult
  • ClosestFacilityRoute
  • ClosestFacilityTask
  • Facility
  • Graphic
  • GraphicsOverlay
  • Incident
  • MapView

Tags

incident, network analysis, route, search

Sample Code

ClosestFacility.cppClosestFacility.cppClosestFacility.hClosestFacility.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
// [WriteFile Name=FindClosestFacilityToAnIncidentInteractive, Category=Routing]
// [Legal]
// Copyright 2017 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 "ClosestFacility.h"

// ArcGIS Maps SDK headers
#include "ClosestFacilityParameters.h"
#include "ClosestFacilityResult.h"
#include "ClosestFacilityRoute.h"
#include "ClosestFacilityTask.h"
#include "Error.h"
#include "Facility.h"
#include "Graphic.h"
#include "GraphicListModel.h"
#include "GraphicsOverlay.h"
#include "GraphicsOverlayListModel.h"
#include "Incident.h"
#include "Map.h"
#include "MapQuickView.h"
#include "MapTypes.h"
#include "MapViewTypes.h"
#include "PictureMarkerSymbol.h"
#include "Point.h"
#include "Polyline.h"
#include "SimpleLineSymbol.h"
#include "SimpleMarkerSymbol.h"
#include "SimpleRenderer.h"
#include "SpatialReference.h"
#include "SymbolTypes.h"
#include "Viewpoint.h"

// Qt headers
#include <QFuture>
#include <QUuid>

using namespace Esri::ArcGISRuntime;

const QUrl ClosestFacility::facilityImageUrl(
    QStringLiteral("https://static.arcgis.com/images/Symbols/SafetyHealth/Hospital.png"));

const QUrl ClosestFacility::sanDiegoRegion(
    QStringLiteral("https://sampleserver6.arcgisonline.com/arcgis/rest/services/NetworkAnalysis/SanDiego/NAServer/ClosestFacility"));

ClosestFacility::ClosestFacility(QQuickItem* parent /* = nullptr */):
  QQuickItem(parent),
  m_task(new ClosestFacilityTask(sanDiegoRegion, this))
{
}

ClosestFacility::~ClosestFacility() = default;

void ClosestFacility::init()
{
  qmlRegisterType<MapQuickView>("Esri.Samples", 1, 0, "MapView");
  qmlRegisterType<ClosestFacility>("Esri.Samples", 1, 0, "ClosestFacilitySample");
}

void ClosestFacility::componentComplete()
{
  QQuickItem::componentComplete();

  // find QML MapView component
  m_mapView = findChild<MapQuickView*>("mapView");
  m_mapView->setWrapAroundMode(WrapAroundMode::Disabled);

  // Create a map using the streets basemap
  m_map = new Map(BasemapStyle::ArcGISStreets, this);

  // set view to be over San Diego
  m_map->setInitialViewpoint(Viewpoint(Point(-13041154, 3858170, SpatialReference(3857)), 1e5));

  // Set map to map view
  m_mapView->setMap(m_map);

  createFacilities();
  createGraphics();

  connect(m_task, &ClosestFacilityTask::doneLoading, this, [this] (const Error& loadError)
  {
    if (!loadError.isEmpty())
      return;

    if (m_task->loadStatus() != LoadStatus::Loaded)
      return;

    setupRouting();
  });

  m_task->load();
}

bool ClosestFacility::busy() const
{
  return m_busy;
}

QString ClosestFacility::message() const
{
  return m_message;
}

void ClosestFacility::setBusy(bool val)
{
  if (m_busy == val)
    return;

  m_message.clear();
  m_busy = val;
  emit busyChanged();
  emit messageChanged();
}

void ClosestFacility::createFacilities()
{
  // List of facilities to be placed around San Diego area
  m_facilities.append(Facility(Point(-1.3042129900625112E7, 3860127.9479775648, SpatialReference::webMercator())));
  m_facilities.append(Facility(Point(-1.3042193400557665E7, 3862448.873041752, SpatialReference::webMercator())));
  m_facilities.append(Facility(Point(-1.3046882875518233E7, 3862704.9896770366, SpatialReference::webMercator())));
  m_facilities.append(Facility(Point(-1.3040539754780494E7, 3862924.5938606677, SpatialReference::webMercator())));
  m_facilities.append(Facility(Point(-1.3042571225655518E7, 3858981.773018156, SpatialReference::webMercator())));
  m_facilities.append(Facility(Point(-1.3039784633928463E7, 3856692.5980474586, SpatialReference::webMercator())));
  m_facilities.append(Facility(Point(-1.3049023883956768E7, 3861993.789732541, SpatialReference::webMercator())));
}

void ClosestFacility::createGraphics()
{
  // create a symbol for the graphics
  PictureMarkerSymbol* facilitySymbol = new PictureMarkerSymbol(facilityImageUrl, this);
  facilitySymbol->setHeight(30);
  facilitySymbol->setWidth(30);

  // create a graphics overlay for the facilities and add a renderer for the symbol
  m_facilityOverlay = new GraphicsOverlay(this);
  SimpleRenderer* facilityRenderer = new SimpleRenderer(facilitySymbol, this);
  m_facilityOverlay->setRenderer(facilityRenderer);

  // add a graphic at the location of each of the facilities
  for (const Facility& facility : std::as_const(m_facilities))
  {
    Graphic* facilityGraphic = new Graphic(facility.geometry(), this);
    m_facilityOverlay->graphics()->append(facilityGraphic);
  }

  // add the overlay to the map view
  m_mapView->graphicsOverlays()->append(m_facilityOverlay);

  // create a symbol for the route graphic
  float lineWidth = 2.0f;
  SimpleLineSymbol* routeSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle::Solid, Qt::blue, lineWidth, this);

  // create a graphics overlay for the routes and add a renderer for the symbol
  m_resultsOverlay = new GraphicsOverlay(this);
  SimpleRenderer* routeRenderer = new SimpleRenderer(routeSymbol, this);
  m_resultsOverlay->setRenderer(routeRenderer);

  // add the overlay to the map view
  m_mapView->graphicsOverlays()->append(m_resultsOverlay);

  // add a graphic to the route overlay
  m_routeGraphic = new Graphic(this);
  m_resultsOverlay->graphics()->append(m_routeGraphic);

  // create a symbol for the incident graphics
  SimpleMarkerSymbol* incidentSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle::Cross, Qt::black, 20, this);

  // create a graphics overlay for the incidents and add a renderer for the symbol
  m_incidentsOverlay = new GraphicsOverlay(this);
  SimpleRenderer* incidentRenderer = new SimpleRenderer(incidentSymbol, this);
  m_incidentsOverlay->setRenderer(incidentRenderer);

  // add the overlay to the map view
  m_mapView->graphicsOverlays()->append(m_incidentsOverlay);

  // add a graphic to the incident overlay
  m_incidentGraphic = new Graphic(this);
  m_incidentsOverlay->graphics()->append(m_incidentGraphic);
}

void ClosestFacility::setupRouting()
{
  connect(m_mapView, &MapQuickView::mouseClicked, this, [this](QMouseEvent& mouseEvent)
  {
    if (busy())
      return;

    Point mapPoint = m_mapView->screenToLocation(mouseEvent.position().x(), mouseEvent.position().y());
    Point incidentPoint(mapPoint.x(), mapPoint.y(), SpatialReference::webMercator());

    m_incidentGraphic->setGeometry(incidentPoint);

    solveRoute(incidentPoint);
  });

  setBusy(true);
  m_task->createDefaultParametersAsync().then(this, [this](const ClosestFacilityParameters& defaultParameters)
  {
    setBusy(false);

    m_facilityParams = defaultParameters;
    m_facilityParams.setFacilities(m_facilities);
  });

}

void ClosestFacility::solveRoute(const Point& incidentPoint)
{
  m_facilityParams.clearIncidents();
  m_facilityParams.setIncidents(QList<Incident> {Incident(incidentPoint)});

  setBusy(true);
  // find the closest facility to the incident
  m_task->solveClosestFacilityAsync(m_facilityParams).then(this, [this](const ClosestFacilityResult& closestFacilityResult)
  {
    setBusy(false);

    if (closestFacilityResult.isEmpty())
    {
      m_message = "Incident not within San Diego Area!";
      emit messageChanged();
    }

    QList<int> rankedList = closestFacilityResult.rankedFacilityIndexes(0);
    int closestFacilityIdx = rankedList.first();

    int incidentIndex = 0; // 0 since there is just 1 incident at a time
    ClosestFacilityRoute route = closestFacilityResult.route(closestFacilityIdx, incidentIndex);

    m_routeGraphic->setGeometry(route.routeGeometry());
  });
}

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