Find routes from several locations to the respective closest facility.

Use case
Quickly and accurately determining the most efficient route between a location and a facility is a frequently encountered task. For example, a city’s fire department may need to know which fire stations in the vicinity offer the quickest routes to multiple fires. Solving for the closest fire station to the fire’s location using an impedance of “travel time” would provide this information.
How to use the sample
Click ‘Solve Routes’ to solve and display the route from each incident (fire) to the nearest facility (fire station). Click ‘Reset’ to clear the results.
How it works
- Create a
ClosestFacilityTaskusing a URL from an online service. - Get the default set of
ClosestFacilityParametersfrom the task:closestFacilityTask.createDefaultParametersAsync(). - Create
ServiceFeatureTables for both facilities incidents. - Add all facilities to the task parameters:
closestFacilityParameters.setFacilitiesWithFeatureTable(facilitiesFeatureTable, parameters). - Add all incidents to the task parameters:
closestFacilityParameters.setIncidentsWithFeatureTable(incidentsFeatureTable, parameters). - Get
ClosestFacilityResultby solving the task with the provided parameters:closestFacilityTask.solveClosestFacilityAsync(closestFacilityParameters). - Find the closest facility for each incident by iterating over the list of
Incidents. - Display the route as a
Graphicusing theclosestFacilityRoute.routeGeometry().
Relevant API
- ClosestFacilityParameters
- ClosestFacilityResult
- ClosestFacilityRoute
- ClosestFacilityTask
- Facility
- Graphic
- GraphicsOverlay
- Incident
Tags
incident, network analysis, route, search
Sample Code
// [WriteFile Name=FindClosestFacilityToMultipleIncidentsService, Category=Routing]// [Legal]// Copyright 2019 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 "FindClosestFacilityToMultipleIncidentsService.h"
// ArcGIS Maps SDK headers#include "ClosestFacilityParameters.h"#include "ClosestFacilityResult.h"#include "ClosestFacilityRoute.h"#include "ClosestFacilityTask.h"#include "Envelope.h"#include "Error.h"#include "FeatureLayer.h"#include "GeometryEngine.h"#include "Graphic.h"#include "GraphicListModel.h"#include "GraphicsOverlay.h"#include "GraphicsOverlayListModel.h"#include "LayerListModel.h"#include "Map.h"#include "MapQuickView.h"#include "MapTypes.h"#include "PictureMarkerSymbol.h"#include "Polyline.h"#include "QueryParameters.h"#include "ServiceFeatureTable.h"#include "SimpleLineSymbol.h"#include "SimpleRenderer.h"#include "SymbolTypes.h"
// Qt headers#include <QFuture>#include <QUuid>
using namespace Esri::ArcGISRuntime;
FindClosestFacilityToMultipleIncidentsService::FindClosestFacilityToMultipleIncidentsService(QObject* parent /* = nullptr */): QObject(parent), m_map(new Map(BasemapStyle::ArcGISStreetsRelief, this)), m_task(new ClosestFacilityTask(QUrl("https://sampleserver6.arcgisonline.com/arcgis/rest/services/NetworkAnalysis/SanDiego/NAServer/ClosestFacility"), this)), m_resultsOverlay(new GraphicsOverlay(this)){ // enable busy indicator while loading m_busy = true;
createSymbols();
createFeatureLayers();
connect(m_task, &ClosestFacilityTask::doneLoading, this, [this](const Error& e) { if (!e.isEmpty()) { qDebug() << e.message(); return; } setupRouting(); }); m_task->load();}
FindClosestFacilityToMultipleIncidentsService::~FindClosestFacilityToMultipleIncidentsService() = default;
void FindClosestFacilityToMultipleIncidentsService::init(){ // Register the map view for QML qmlRegisterType<MapQuickView>("Esri.Samples", 1, 0, "MapView"); qmlRegisterType<FindClosestFacilityToMultipleIncidentsService>("Esri.Samples", 1, 0, "FindClosestFacilityToMultipleIncidentsServiceSample");}
MapQuickView* FindClosestFacilityToMultipleIncidentsService::mapView() const{ return m_mapView;}
// Set the view (created in QML)void FindClosestFacilityToMultipleIncidentsService::setMapView(MapQuickView* mapView){ if (!mapView || mapView == m_mapView) return;
m_mapView = mapView; m_mapView->setMap(m_map);
emit mapViewChanged();}
void FindClosestFacilityToMultipleIncidentsService::createSymbols(){ m_facilitySymbol = new PictureMarkerSymbol(QUrl("https://static.arcgis.com/images/Symbols/SafetyHealth/FireStation.png"), this); m_facilitySymbol->setWidth(30.0f); m_facilitySymbol->setHeight(30.0f);
m_incidentSymbol = new PictureMarkerSymbol(QUrl("https://static.arcgis.com/images/Symbols/SafetyHealth/esriCrimeMarker_56_Gradient.png"), this); m_incidentSymbol->setWidth(30.0f); m_incidentSymbol->setHeight(30.0f);
m_routeSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle::Solid, Qt::blue, 2.0f, this);}
void FindClosestFacilityToMultipleIncidentsService::createFeatureLayers(){ m_facilitiesFeatureTable = new ServiceFeatureTable(QUrl("https://services2.arcgis.com/ZQgQTuoyBrtmoGdP/ArcGIS/rest/services/San_Diego_Facilities/FeatureServer/0"), this); m_facilitiesFeatureLayer = new FeatureLayer(m_facilitiesFeatureTable, this); m_facilitiesFeatureLayer->setRenderer(new SimpleRenderer(m_facilitySymbol, this));
m_incidentsFeatureTable = new ServiceFeatureTable(QUrl("https://services2.arcgis.com/ZQgQTuoyBrtmoGdP/ArcGIS/rest/services/San_Diego_Incidents/FeatureServer/0"), this); m_incidentsFeatureLayer = new FeatureLayer(m_incidentsFeatureTable, this); m_incidentsFeatureLayer->setRenderer(new SimpleRenderer(m_incidentSymbol, this));
// connect to the doneLoading signal which calls the slot to set the view point geometry connect(m_facilitiesFeatureTable, &ServiceFeatureTable::doneLoading, this, &FindClosestFacilityToMultipleIncidentsService::setViewpointGeometry); connect(m_incidentsFeatureTable, &ServiceFeatureTable::doneLoading, this, &FindClosestFacilityToMultipleIncidentsService::setViewpointGeometry);
m_facilitiesFeatureTable->load(); m_incidentsFeatureTable->load();}
void FindClosestFacilityToMultipleIncidentsService::setupRouting(){ m_task->createDefaultParametersAsync().then(this, [this](const ClosestFacilityParameters& defaultParameters) { QueryParameters params; params.setWhereClause("1=1"); m_facilityParams = defaultParameters; m_facilityParams.setFacilitiesWithFeatureTable(m_facilitiesFeatureTable, params); m_facilityParams.setIncidentsWithFeatureTable(m_incidentsFeatureTable, params);
m_busy = false; m_solveButtonEnabled = true; emit busyChanged(); emit solveButtonChanged(); });}
void FindClosestFacilityToMultipleIncidentsService::setViewpointGeometry(const Error& e){ if (!e.isEmpty()) { qDebug() << e.message(); return; }
// proceed only if both layers have been loaded if ((m_facilitiesFeatureTable->loadStatus() != LoadStatus::Loaded) || (m_incidentsFeatureTable->loadStatus() != LoadStatus::Loaded)) return;
// return if set viewpoint future has already been created if (m_setViewpointFuture.isValid()) return;
m_mapView->map()->operationalLayers()->append(m_facilitiesFeatureLayer); m_mapView->map()->operationalLayers()->append(m_incidentsFeatureLayer);
m_setViewpointFuture = m_mapView->setViewpointGeometryAsync(GeometryEngine::unionOf(m_facilitiesFeatureLayer->fullExtent(), m_incidentsFeatureLayer->fullExtent()), 20);}
void FindClosestFacilityToMultipleIncidentsService::solveRoute(){ m_busy = true; m_solveButtonEnabled = false; emit busyChanged(); emit solveButtonChanged();
m_task->solveClosestFacilityAsync(m_facilityParams).then(this, [this]( const ClosestFacilityResult& closestFacilityResult) { if (closestFacilityResult.isEmpty()) { qDebug() << "Empty result"; return; }
// finding the closest facility for each incident to create a route graphic between each pair for (int incidentIndex = 0; incidentIndex < m_incidentsFeatureTable->numberOfFeatures(); incidentIndex++) { const auto indexes = closestFacilityResult.rankedFacilityIndexes(incidentIndex); const int closestFacilityIndex = indexes.first(); const ClosestFacilityRoute route = closestFacilityResult.route(closestFacilityIndex, incidentIndex); Graphic* m_routeGraphic = new Graphic(route.routeGeometry(), m_routeSymbol, this);
m_resultsOverlay->graphics()->append(m_routeGraphic); }
m_mapView->graphicsOverlays()->append(m_resultsOverlay); m_resetButtonEnabled = true; emit resetButtonChanged(); m_busy = false; emit busyChanged(); });}
void FindClosestFacilityToMultipleIncidentsService::resetGO(){ m_mapView->graphicsOverlays()->clear(); m_resetButtonEnabled = false; m_solveButtonEnabled = true; emit solveButtonChanged(); emit resetButtonChanged();}// [WriteFile Name=FindClosestFacilityToMultipleIncidentsService, Category=Routing]// [Legal]// Copyright 2019 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]
#ifndef FINDCLOSESTFACILITYTOMULTIPLEINCIDENTSSERVICE_H#define FINDCLOSESTFACILITYTOMULTIPLEINCIDENTSSERVICE_H
// ArcGIS Maps SDK headers#include "ClosestFacilityParameters.h"
// Qt headers#include <QFuture>#include <QObject>
namespace Esri::ArcGISRuntime{class Map;class MapQuickView;class ServiceFeatureTable;class FeatureLayer;class GraphicsOverlay;class Graphic;class ClosestFacilityTask;class Facility;class Incident;class PictureMarkerSymbol;class SimpleLineSymbol;class QueryParameters;class Error;}
Q_MOC_INCLUDE("MapQuickView.h")Q_MOC_INCLUDE("Error.h")
class FindClosestFacilityToMultipleIncidentsService : public QObject{ Q_OBJECT
Q_PROPERTY(Esri::ArcGISRuntime::MapQuickView* mapView READ mapView WRITE setMapView NOTIFY mapViewChanged) Q_PROPERTY(bool busy MEMBER m_busy NOTIFY busyChanged) Q_PROPERTY(bool solveButton MEMBER m_solveButtonEnabled NOTIFY solveButtonChanged) Q_PROPERTY(bool resetButton MEMBER m_resetButtonEnabled NOTIFY resetButtonChanged)
public: explicit FindClosestFacilityToMultipleIncidentsService(QObject* parent = nullptr); ~FindClosestFacilityToMultipleIncidentsService();
static void init(); Q_INVOKABLE void solveRoute(); Q_INVOKABLE void resetGO();
signals: void mapViewChanged(); void busyChanged(); void solveButtonChanged(); void resetButtonChanged();
private slots: void setViewpointGeometry(const Esri::ArcGISRuntime::Error& e);
private: Esri::ArcGISRuntime::MapQuickView* mapView() const; void setMapView(Esri::ArcGISRuntime::MapQuickView* mapView); void createSymbols(); void createFeatureLayers(); void setupRouting();
Esri::ArcGISRuntime::Map* m_map = nullptr; Esri::ArcGISRuntime::MapQuickView* m_mapView = nullptr; Esri::ArcGISRuntime::ServiceFeatureTable* m_facilitiesFeatureTable = nullptr; Esri::ArcGISRuntime::ServiceFeatureTable* m_incidentsFeatureTable = nullptr; Esri::ArcGISRuntime::FeatureLayer* m_facilitiesFeatureLayer = nullptr; Esri::ArcGISRuntime::FeatureLayer* m_incidentsFeatureLayer = nullptr; Esri::ArcGISRuntime::PictureMarkerSymbol* m_facilitySymbol = nullptr; Esri::ArcGISRuntime::PictureMarkerSymbol* m_incidentSymbol = nullptr; Esri::ArcGISRuntime::SimpleLineSymbol* m_routeSymbol = nullptr; Esri::ArcGISRuntime::ClosestFacilityTask* m_task = nullptr; Esri::ArcGISRuntime::GraphicsOverlay* m_resultsOverlay = nullptr; QFuture<bool> m_setViewpointFuture; Esri::ArcGISRuntime::ClosestFacilityParameters m_facilityParams;
bool m_busy = false; bool m_solveButtonEnabled = false; bool m_resetButtonEnabled = false;};
#endif // FINDCLOSESTFACILITYTOMULTIPLEINCIDENTSSERVICE_H// [WriteFile Name=FindClosestFacilityToMultipleIncidentsService, Category=Routing]// [Legal]// Copyright 2019 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 QtQuickimport QtQuick.Controlsimport QtQuick.Layoutsimport Esri.Samples
Item {
// add a mapView component MapView { id: view anchors.fill: parent
Component.onCompleted: { // Set the focus on MapView to initially enable keyboard navigation forceActiveFocus(); }
// background for buttons Rectangle { anchors { margins: 5 left: parent.left top: parent.top } width: childrenRect.width height: childrenRect.height color: "#000000" opacity: .70 radius: 5
// catch mouse signals from propagating to parent MouseArea { anchors.fill: parent onClicked: mouse => mouse.accepted = true onWheel: wheel => wheel.accepted = true }
// column layout for solve and reset buttons ColumnLayout { Button { id: solveButton text: qsTr("Solve Routes") Layout.margins: 2 Layout.fillWidth: true enabled: closestFacilityModel.solveButton onClicked: closestFacilityModel.solveRoute(); }
Button { id: resetButton text: qsTr("Reset") Layout.margins: 2 Layout.fillWidth: true enabled: closestFacilityModel.resetButton onClicked: closestFacilityModel.resetGO(); } } } }
BusyIndicator { anchors.centerIn: parent running: closestFacilityModel.busy }
// Declare the C++ instance which creates the map etc. and supply the view FindClosestFacilityToMultipleIncidentsServiceSample { id: closestFacilityModel mapView: view }}// [Legal]// Copyright 2019 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]
// sample headers#include "FindClosestFacilityToMultipleIncidentsService.h"
// ArcGIS Maps SDK headers#include "ArcGISRuntimeEnvironment.h"
// Qt headers#include <QDir>#include <QGuiApplication>#include <QQmlApplicationEngine>
// Platform specific headers#ifdef Q_OS_WIN#include <Windows.h>#endif
#define STRINGIZE(x) #x#define QUOTE(x) STRINGIZE(x)
int main(int argc, char *argv[]){ Esri::ArcGISRuntime::ArcGISRuntimeEnvironment::setUseLegacyAuthentication(false); QGuiApplication app(argc, argv); app.setApplicationName(QString("FindClosestFacilityToMultipleIncidentsService"));
// Use of ArcGIS location services, such as basemap styles, geocoding, and routing services, // requires an access token. For more information see // https://links.esri.com/arcgis-runtime-security-auth.
// The following methods grant an access token:
// 1. User authentication: Grants a temporary access token associated with a user's ArcGIS account. // To generate a token, a user logs in to the app with an ArcGIS account that is part of an // organization in ArcGIS Online or ArcGIS Enterprise.
// 2. API key authentication: Get a long-lived access token that gives your application access to // ArcGIS location services. Go to the tutorial at https://links.esri.com/create-an-api-key. // Copy the API Key access token.
const QString accessToken = QString("");
if (accessToken.isEmpty()) { qWarning() << "Use of ArcGIS location services, such as the basemap styles service, requires" << "you to authenticate with an ArcGIS account or set the API Key property."; } else { Esri::ArcGISRuntime::ArcGISRuntimeEnvironment::setApiKey(accessToken); }
// Initialize the sample FindClosestFacilityToMultipleIncidentsService::init();
QString arcGISRuntimeImportPath = QUOTE(ARCGIS_RUNTIME_IMPORT_PATH);
#if defined(LINUX_PLATFORM_REPLACEMENT) // on some linux platforms the string 'linux' is replaced with 1 // fix the replacement paths which were created QString replaceString = QUOTE(LINUX_PLATFORM_REPLACEMENT); arcGISRuntimeImportPath = arcGISRuntimeImportPath.replace(replaceString, "linux", Qt::CaseSensitive);#endif
// Initialize application view QQmlApplicationEngine engine; // Add the import Path engine.addImportPath(QDir(QCoreApplication::applicationDirPath()).filePath("qml")); // Add the Runtime and Extras path engine.addImportPath(arcGISRuntimeImportPath);
// Set the source engine.load(QUrl("qrc:/Samples/Routing/FindClosestFacilityToMultipleIncidentsService/main.qml"));
return app.exec();}// Copyright 2019 ESRI//// All rights reserved under the copyright laws of the United States// and applicable international laws, treaties, and conventions.//// You may freely redistribute and use this sample code, with or// without modification, provided you include the original copyright// notice and use restrictions.//// See the Sample code usage restrictions document for further information.//
import QtQuick.Controlsimport Esri.Samples
ApplicationWindow { visible: true width: 800 height: 600
FindClosestFacilityToMultipleIncidentsService { anchors.fill: parent }}