Find closest facility from point

View on GitHub

Find routes from several locations to the respective closest facility.

Image of find closest facility from point

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 firestations 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

Tap on the 'Solve Routes' button to solve and display the route from each incident (fire) to the nearest facility (fire station).

How it works

  1. Create a ClosestFacilityTask using a URL from an online service.
  2. Create a FeatureTable for each of the Facilities and Incidents services using ServiceFeatureTable.withUri(uri).
  3. Get the default set of ClosestFacilityParameters from the task using ClosestFacilityTask.createDefaultParameters().
  4. Add the facilities table to the task parameters, along with QueryParameters defined to query all features using ClosestFacilityParameters.setFacilitiesWithFeatureTable(featureTable, queryParameters).
  5. Add the incidents table to the task parameters, along with QueryParameters defined to query all features using ClosestFacilityParameters.setIncidentsWithFeatureTable(featureTable, queryParameters).
  6. Get the ClosestFacilityResult by solving the task with the provided parameters: ClosestFacilityTask.solveClosestFacility(closestFacilityParameters).
  7. Find the closest facility for each incident by iterating over the list of result.incidents.
  8. Display the route as a Graphic using the routeGraphicsOverlay.graphics.add(routeGraphic).

Relevant API

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

Tags

incident, network analysis, route, search

Sample Code

find_closest_facility_from_point.dart
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
//
// Copyright 2024 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
//
//   https://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.
//

import 'package:arcgis_maps/arcgis_maps.dart';
import 'package:flutter/material.dart';

import '../../utils/sample_state_support.dart';

class FindClosestFacilityFromPoint extends StatefulWidget {
  const FindClosestFacilityFromPoint({super.key});

  @override
  State<FindClosestFacilityFromPoint> createState() =>
      _FindClosestFacilityFromPointState();
}

class _FindClosestFacilityFromPointState
    extends State<FindClosestFacilityFromPoint> with SampleStateSupport {
  // Create the URIs for the fire station and fire images, as well as the URIs for the facilities and incidents layers.
  static final _fireStationImageUri = Uri.parse(
    'https://static.arcgis.com/images/Symbols/SafetyHealth/FireStation.png',
  );
  static final _fireImageUri = Uri.parse(
    'https://static.arcgis.com/images/Symbols/SafetyHealth/esriCrimeMarker_56_Gradient.png',
  );
  static final _facilitiesLayerUri = Uri.parse(
    'https://services2.arcgis.com/ZQgQTuoyBrtmoGdP/ArcGIS/rest/services/San_Diego_Facilities/FeatureServer/0',
  );
  static final _incidentsLayerUri = Uri.parse(
    'https://services2.arcgis.com/ZQgQTuoyBrtmoGdP/ArcGIS/rest/services/San_Diego_Incidents/FeatureServer/0',
  );
  // Create a task for the closest facility service.
  final _closestFacilityTask = ClosestFacilityTask.withUri(
    Uri.parse(
      'https://sampleserver6.arcgisonline.com/arcgis/rest/services/NetworkAnalysis/SanDiego/NAServer/ClosestFacility',
    ),
  );
  // Create a controller for the map view.
  final _mapViewController = ArcGISMapView.createController();
  // Create a graphics overlay for the route.
  final _routeGraphicsOverlay = GraphicsOverlay();
  // Create a flag to track whether the route has been solved.
  var _routeSolved = false;
  // A flag for when the map view is ready and controls can be used.
  var _ready = false;
  // Create parameters for the closest facility task.
  late final ClosestFacilityParameters _closestFacilityParameters;
  // Create a symbol for the route line.
  final _routeLineSymbol = SimpleLineSymbol(
    style: SimpleLineSymbolStyle.solid,
    color: Colors.blue,
    width: 5.0,
  );

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        top: false,
        child: Stack(
          children: [
            Column(
              children: [
                Expanded(
                  // Add a map view to the widget tree and set a controller.
                  child: ArcGISMapView(
                    controllerProvider: () => _mapViewController,
                    onMapViewReady: onMapViewReady,
                  ),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    // Create buttons to solve the routes and reset the graphics.
                    ElevatedButton(
                      onPressed: !_routeSolved ? solveRoutes : null,
                      child: const Text('Solve Routes'),
                    ),
                    ElevatedButton(
                      onPressed: _routeSolved ? resetRoutes : null,
                      child: const Text('Reset'),
                    ),
                  ],
                ),
              ],
            ),
            // Display a progress indicator and prevent interaction until state is ready.
            Visibility(
              visible: !_ready,
              child: SizedBox.expand(
                child: Container(
                  color: Colors.white30,
                  child: const Center(child: CircularProgressIndicator()),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  void onMapViewReady() async {
    // Create a map with the ArcGIS Streets basemap style.
    final map = ArcGISMap.withBasemapStyle(BasemapStyle.arcGISStreets);

    // Create feature table for the facilities layer.
    final facilitiesFeatureTable =
        ServiceFeatureTable.withUri(_facilitiesLayerUri);
    // Create a marker symbol for the facilities.
    final facilitiesMarkerSymbol =
        PictureMarkerSymbol.withUri(_fireStationImageUri)
          ..width = 30
          ..height = 30;
    // Create a feature layer for the facilities.
    final facilitiesLayer =
        FeatureLayer.withFeatureTable(facilitiesFeatureTable)
          ..renderer = SimpleRenderer(symbol: facilitiesMarkerSymbol);

    // Create feature table for the incidents layer.
    final incidentsFeatureTable =
        ServiceFeatureTable.withUri(_incidentsLayerUri);
    // Create a marker symbol for the incidents.
    final incidentsMarkerSymbol = PictureMarkerSymbol.withUri(_fireImageUri)
      ..width = 30
      ..height = 30;
    // Create a feature layer for the incidents.
    final incidentsLayer = FeatureLayer.withFeatureTable(incidentsFeatureTable)
      ..renderer = SimpleRenderer(symbol: incidentsMarkerSymbol);

    // Add the layers to the map.
    map.operationalLayers.addAll([facilitiesLayer, incidentsLayer]);

    // Set the map on the map view controller.
    _mapViewController.arcGISMap = map;

    // Add the route graphics overlay to the map view controller.
    _routeGraphicsOverlay.opacity = 0.75;
    _mapViewController.graphicsOverlays.add(_routeGraphicsOverlay);

    // Load the layers
    await Future.wait([
      facilitiesLayer.load(),
      incidentsLayer.load(),
    ]);

    // Get the extent from the layers and use the combination as the viewpoint geometry.
    final mapExtent = GeometryEngine.combineExtents(
      geometry1: facilitiesLayer.fullExtent!,
      geometry2: incidentsLayer.fullExtent!,
    );

    // Set the viewpoint geometry on the map view controller.
    _mapViewController.setViewpointGeometry(mapExtent, paddingInDiPs: 30);

    // Generate the closest facility parameters.
    _closestFacilityParameters = await generateClosestFacilityParameters(
      facilitiesFeatureTable,
      incidentsFeatureTable,
    );

    // Set the initialized flag to true.
    setState(() => _ready = true);
  }

  FeatureLayer buildFeatureLayer(Uri tableUri, Uri imageUri) {
    // Create a feature table and feature layer for the facilities or incidents.
    final featureTable = ServiceFeatureTable.withUri(tableUri);
    final markerSymbol = PictureMarkerSymbol.withUri(imageUri)
      ..width = 30
      ..height = 30;
    final featureLayer = FeatureLayer.withFeatureTable(featureTable)
      ..renderer = SimpleRenderer(symbol: markerSymbol);

    return featureLayer;
  }

  Future<ClosestFacilityParameters> generateClosestFacilityParameters(
    FeatureTable facilitiesFeatureTable,
    FeatureTable incidentsFeatureTable,
  ) async {
    // Create query parameters to get all features.
    final featureQueryParams = QueryParameters()..whereClause = '1=1';
    // Create default parameters for the closest facility task.
    final parameters = await _closestFacilityTask.createDefaultParameters()
      ..setFacilitiesWithFeatureTable(
        featureTable: facilitiesFeatureTable as ArcGISFeatureTable,
        queryParameters: featureQueryParams,
      )
      ..setIncidentsWithFeatureTable(
        featureTable: incidentsFeatureTable as ArcGISFeatureTable,
        queryParameters: featureQueryParams,
      );

    return parameters;
  }

  void solveRoutes() async {
    setState(() => _ready = false);
    // Solve the closest facility task with the parameters.
    final result = await _closestFacilityTask.solveClosestFacility(
      _closestFacilityParameters,
    );
    for (var incidentIdx = 0;
        incidentIdx < result.incidents.length;
        ++incidentIdx) {
      final rankedFacilities =
          result.getRankedFacilityIndexes(incidentIndex: incidentIdx);
      if (rankedFacilities.isEmpty) {
        continue;
      }

      // Get the route to the closest facility.
      final closestFacilityIdx = rankedFacilities.first;
      final routeToFacility = result.getRoute(
        facilityIndex: closestFacilityIdx,
        incidentIndex: incidentIdx,
      );
      // Add the route to the graphics overlay.
      if (routeToFacility != null) {
        final routeGraphic = Graphic(
          geometry: routeToFacility.routeGeometry,
          symbol: _routeLineSymbol,
        );
        _routeGraphicsOverlay.graphics.add(routeGraphic);
      }
    }

    // Set the route solved flag to true.
    setState(() {
      _ready = true;
      _routeSolved = true;
    });
  }

  void resetRoutes() {
    // Clear the graphics overlay and set the route solved flag to false.
    _routeGraphicsOverlay.graphics.clear();
    setState(() => _routeSolved = false);
  }
}

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