Service area

View on GitHubSample viewer app

Find the service area within a network from a given point.

screenshot

Use case

A service area shows locations that can be reached from a facility based off a certain impedance, such as travel time or distance. Barriers can increase impedance by either adding to the time it takes to pass through the barrier or by altogether preventing passage.

You might calculate the region around a hospital in which ambulances can service in 30 min or less.

How to use sample

  • In order to find any services areas at least one ServiceAreaFaciltiy needs to be added.
  • To add a facility, select "Facility" from the combo-box then click anywhere on the MapView.
  • To add a barrier, select "Barrier" from the combo-box and click multiple locations on the MapView to draw a barrier.
  • To start a new line in a distinct location, click "new barrier"
  • To show service areas around facilities that were added, click the "Solve" button.
  • The "Reset" button, clears all graphics and resets the ServiceAreaTask.

How it works

  1. Create a new ServiceAreaTask from a network service.
  2. Create default ServiceAreaParameters from the service area task.
  3. Set the parameters to return polygons (true) to return all service areas.
  4. Add a ServiceAreaFacility to the parameters.
  5. Get the ServiceAreaResult by solving the service area task using the parameters.
  6. Get any ServiceAreaPolygons that were returned, serviceAreaResult.getResultPolygons(facilityIndex).
  7. Display the service area polygons as graphics in a GraphicsOverlay on the MapView.

Relevant API

  • PolylineBarrier
  • ServiceAreaFacility
  • ServiceAreaParameters
  • ServiceAreaPolygon
  • ServiceAreaResult
  • ServiceAreaTask

Tags

barriers, facilities, impedance, logistics, routing

Sample Code

ServiceArea.cppServiceArea.cppServiceArea.hServiceArea.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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
// [WriteFile Name=ServiceArea, 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 "ServiceArea.h"

// ArcGIS Maps SDK headers
#include "Error.h"
#include "Graphic.h"
#include "GraphicListModel.h"
#include "GraphicsOverlay.h"
#include "GraphicsOverlayListModel.h"
#include "Map.h"
#include "MapQuickView.h"
#include "MapTypes.h"
#include "MapViewTypes.h"
#include "NetworkAnalystTypes.h"
#include "PictureMarkerSymbol.h"
#include "Point.h"
#include "Polygon.h"
#include "Polyline.h"
#include "PolylineBarrier.h"
#include "PolylineBuilder.h"
#include "ServiceAreaFacility.h"
#include "ServiceAreaPolygon.h"
#include "ServiceAreaResult.h"
#include "ServiceAreaTask.h"
#include "SimpleFillSymbol.h"
#include "SimpleLineSymbol.h"
#include "SimpleRenderer.h"
#include "SpatialReference.h"
#include "SymbolTypes.h"
#include "Viewpoint.h"

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

using namespace Esri::ArcGISRuntime;

ServiceArea::ServiceArea(QQuickItem* parent /* = nullptr */):
  QQuickItem(parent),
  m_task(new ServiceAreaTask(
           QUrl("https://sampleserver6.arcgisonline.com/arcgis/rest/services/NetworkAnalysis/SanDiego/NAServer/ServiceArea"), this))
{
}

ServiceArea::~ServiceArea() = default;

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

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

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

  // set view to be over San Diego
  m_map = new Map(BasemapStyle::ArcGISStreets, this);
  m_map->setInitialViewpoint(Viewpoint(Point(-13041154, 3858170, SpatialReference(3857)), 1e5));

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

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

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

    setupRouting();
  });
  m_task->load();

  setupGraphics();
}

void ServiceArea::setFacilityMode()
{
  m_mode = SampleMode::Facility;
}

void ServiceArea::setBarrierMode()
{
  m_mode = SampleMode::Barrier;

  if (m_barrierBuilder)
    return;

  m_barrierBuilder = new PolylineBuilder(SpatialReference::webMercator(), this);
}

void ServiceArea::solveServiceArea()
{
  setBusy(true);

  m_parameters.clearFacilities();
  m_parameters.clearPolylineBarriers();

  GraphicListModel* facilitiesGraphics = m_facilitiesOverlay->graphics();
  if (!facilitiesGraphics || facilitiesGraphics->rowCount() == 0)
  {
    setBusy(false);
    m_message = "At least 1 Facility is required.";
    emit messageChanged();
    return;
  }

  QList<ServiceAreaFacility> facilities;
  facilities.reserve(facilitiesGraphics->rowCount());
  for (int f = 0; f < facilitiesGraphics->rowCount(); ++f)
  {
    Graphic* g = facilitiesGraphics->at(f);
    if (!g)
      continue;

    facilities.append(ServiceAreaFacility(geometry_cast<Point>(g->geometry())));
  }
  m_parameters.setFacilities(facilities);

  GraphicListModel* barrierGraphics = m_barrierOverlay->graphics();
  QList<PolylineBarrier> barriers;
  barriers.reserve(barrierGraphics->rowCount());
  for (int b = 0; b < barrierGraphics->rowCount(); ++b)
  {
    Graphic* g = barrierGraphics->at(b);
    if (!g)
      continue;

    barriers.append(PolylineBarrier(geometry_cast<Polyline>(g->geometry())));
  }

  if (!barriers.isEmpty())
    m_parameters.setPolylineBarriers(barriers);

  m_task->solveServiceAreaAsync(m_parameters).then(this, [this](const ServiceAreaResult& serviceAreaResult)
  {
    setBusy(false);
    if (serviceAreaResult.isEmpty())
    {
      m_message = "No Serice Areas calculated!";
      emit messageChanged();
      return;
    }

    int numFacilities = m_facilitiesOverlay->graphics()->size();
    for (int i = 0; i < numFacilities; ++i)
    {
      const QList<ServiceAreaPolygon> results = serviceAreaResult.resultPolygons(i);
      if (!m_graphicParent)
        m_graphicParent = new QObject(this);
      for (const ServiceAreaPolygon& poly : results)
        m_areasOverlay->graphics()->append(new Graphic(poly.geometry(), m_graphicParent));
    }
  });
}

void ServiceArea::reset()
{
  m_facilitiesOverlay->graphics()->clear();
  m_barrierOverlay->graphics()->clear();
  if (m_barrierBuilder)
  {
    delete m_barrierBuilder;
    m_barrierBuilder = new PolylineBuilder(SpatialReference::webMercator(), this);
  }
  m_areasOverlay->graphics()->clear();
  if (m_graphicParent)
  {
    delete m_graphicParent;
    m_graphicParent = nullptr;
  }
}

void ServiceArea::newBarrier()
{
  if (m_barrierBuilder)
  {
    delete m_barrierBuilder;
    m_barrierBuilder = nullptr;
  }

  setBarrierMode();
  if (!m_graphicParent)
    m_graphicParent = new QObject(this);
  m_barrierOverlay->graphics()->append(new Graphic(m_barrierBuilder->toPolyline(), m_graphicParent));
}

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

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

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

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

void ServiceArea::setupGraphics()
{
  // create a symbol for the incidents
  PictureMarkerSymbol* facilitySymbol = new PictureMarkerSymbol(
        QUrl(QStringLiteral("https://static.arcgis.com/images/Symbols/SafetyHealth/Hospital.png")), this);
  facilitySymbol->setHeight(30);
  facilitySymbol->setWidth(30);

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

  m_mapView->graphicsOverlays()->append(m_facilitiesOverlay);

  // create a symbol for the barriers
  float lineWidth = 3.0f;
  SimpleLineSymbol* lineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle::Solid, Qt::black, lineWidth, this);
  m_barrierOverlay = new GraphicsOverlay(this);
  SimpleRenderer* lineRenderer = new SimpleRenderer(lineSymbol, this);
  m_barrierOverlay->setRenderer(lineRenderer);

  m_mapView->graphicsOverlays()->append(m_barrierOverlay);

  //create a symbol for the service areas
  SimpleFillSymbol* fillSymbol = new SimpleFillSymbol(SimpleFillSymbolStyle::Solid, Qt::green, lineSymbol, this);
  m_areasOverlay = new GraphicsOverlay(this);
  SimpleRenderer* areaRenderer = new SimpleRenderer(fillSymbol, this);
  m_areasOverlay->setRenderer(areaRenderer);
  m_areasOverlay->setOpacity(0.5f);

  m_mapView->graphicsOverlays()->append(m_areasOverlay);
}

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

    switch (m_mode) {
    case SampleMode::Barrier:
    case SampleMode::Facility:
      break;
    default:
      return;
    }

    setBusy(true);

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

    if (m_mode == SampleMode::Barrier)
      handleBarrierPoint(projectedPoint);
    else if(m_mode == SampleMode::Facility)
      handleFacilityPoint(projectedPoint);

    setBusy(false);
  });

  m_task->createDefaultParametersAsync().then(this, [this](const ServiceAreaParameters& defaultParameters)
  {
    m_parameters = defaultParameters;
    m_parameters.setOutputSpatialReference(SpatialReference::webMercator());
    m_parameters.setReturnPolygons(true);
    m_parameters.setPolygonDetail(ServiceAreaPolygonDetail::High);
    setBusy(false);
  });
}

void ServiceArea::handleFacilityPoint(const Point &p)
{
  if (!m_graphicParent)
    m_graphicParent = new QObject(this);
  m_facilitiesOverlay->graphics()->append(new Graphic(p, m_graphicParent));
}

void ServiceArea::handleBarrierPoint(const Point &p)
{
  if (!m_graphicParent)
    m_graphicParent = new QObject(this);
  m_barrierBuilder->addPoint(p);
  // update the geometry for the current barrier - or create 1 if it does not exist
  Graphic* barrier = m_barrierOverlay->graphics()->isEmpty() ?
                       nullptr :
                       m_barrierOverlay->graphics()->last();

  if (barrier)
    barrier->setGeometry(m_barrierBuilder->toPolyline());
  else
    m_barrierOverlay->graphics()->append(new Graphic(m_barrierBuilder->toPolyline(), m_graphicParent));
}

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