Skip to content
View on GitHub

Run a filtered trace to locate operable features that will isolate an area from the flow of network resources.

Image of a utility network with an isolation trace applied to it

Use case

Determine the set of operable features required to stop a network's resource, effectively isolating an area of the network. For example, you can choose to return only accessible and operable valves: ones that are not paved over or rusted shut.

How to use the sample

Tap on one or more features to use as filter barriers or create and set the configuration's filter barriers by selecting a category. Check or uncheck 'Include Isolated Features'. Tap 'Trace' to run a subnetwork-based isolation trace. Tap 'Reset' to clear filter barriers.

How it works

  1. Create a new ArcGISMapView and subscribe to its onTap event.

  2. Create and load a ArcGISMap with a web map portal item that contains a UtilityNetwork.

  3. Load the UtilityNetwork from the ArcGISMap.

  4. Create UtilityTraceParameters with UtilityTraceType.isolation and a starting location from a given asset type and global ID.

  5. Get a default UtilityTraceConfiguration from a given tier in a domain network to set UtilityTraceParameters.traceConfiguration.

  6. Add a GraphicsOverlay with a Graphic that represents this starting location; and another GraphicsOverlay for filter barriers.

  7. Populate the choice list for the 'Filter Barrier: Category exists' from UtilityNetworkDefinition.categories.

  8. When the MapView is tapped, identify which features are at the tap location and add a Graphic that represents a filter barrier.

  9. Create a UtilityElement for the identified feature and add this UtilityElement to a collection of filter barriers.

    • If the element is a junction with more than one terminal, display a terminal picker. Then set the junction's Terminal property with the selected terminal.
    • If an edge, set its fractionAlongLine property using GeometryEngine.fractionAlong.
  10. If Trace is tapped without filter barriers:

    • Create a new UtilityCategoryComparison with the selected category and UtilityCategoryComparisonOperator.exists.
    • Create a new UtilityTraceFilter with this condition as Barriers to set Filter and update includeIsolatedFeatures properties of the default configuration from step 5.
    • Run a UtilityNetwork.trace(parameters).

    If Trace is tapped with filter barriers:

    • Update includeIsolatedFeatures property of the default configuration from step 5.
    • Run a UtilityNetwork.trace(parameters).
  11. For every FeatureLayer in the map, select the features returned with getFeaturesForElements(elements) from the elements matching their NetworkSource.featureTable with the layer's FeatureTable.

Relevant API

  • GeometryEngine.fractionAlong
  • ServiceGeodatabase
  • UtilityCategory
  • UtilityCategoryComparison
  • UtilityCategoryComparisonOperator
  • UtilityDomainNetwork
  • UtilityElement
  • UtilityElementTraceResult
  • UtilityNetwork
  • UtilityNetworkDefinition
  • UtilityTerminal
  • UtilityTier
  • UtilityTraceFilter
  • UtilityTraceParameters
  • UtilityTraceResult
  • UtilityTraceType

About the data

The Naperville gas network feature service contains a utility network used to run the isolation trace shown in this sample. Authentication is required and handled within the sample code.

Additional information

Using utility network on ArcGIS Enterprise 10.8 requires an ArcGIS Enterprise member account licensed with the Utility Network user type extension. Please refer to the utility network services documentation.

Tags

category comparison, condition barriers, filter barriers, isolated features, network analysis, subnetwork trace, trace configuration, trace filter, utility network

Sample Code

run_valve_isolation_trace.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
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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
// Copyright 2025 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:arcgis_maps_sdk_flutter_samples/common/common.dart';
import 'package:arcgis_maps_sdk_flutter_samples/common/token_challenger_handler.dart';
import 'package:flutter/material.dart';

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

  @override
  State<RunValveIsolationTrace> createState() => _RunValveIsolationTraceState();
}

class _RunValveIsolationTraceState extends State<RunValveIsolationTrace>
    with SampleStateSupport {
  // Map view controller for displaying the map.
  final _mapViewController = ArcGISMapView.createController();

  // Feature service for an electric utility network in Naperville, Illinois.
  late UtilityNetwork _utilityNetwork;

  // The trace configuration for the utility network.
  UtilityTraceConfiguration? _configuration;

  /// The starting location for the trace.
  late UtilityElement _startingLocationElement;

  // The parameters for the trace.
  late UtilityTraceParameters _traceParameters;

  // Graphics overlay for displaying filter barriers.
  final _graphicsOverlayBarriers = GraphicsOverlay();

  // Symbols for displaying starting location.
  final _startingPointSymbols = SimpleMarkerSymbol(
    style: SimpleMarkerSymbolStyle.cross,
    size: 20,
    color: const Color.fromARGB(255, 117, 216, 4), // Bright green
  );

  // Symbol for displaying filter barriers.
  final _barrierPointSymbol = SimpleMarkerSymbol(
    style: SimpleMarkerSymbolStyle.x,
    color: Colors.red,
    size: 15,
  );

  // Indicator for loading state.
  var _loading = true;

  // Set to enable/disable trace button.
  var _traceEnabled = false;

  /// Set to enable/disable reset button.
  var _resetEnabled = false;

  // Status message for the banner.
  String? _statusMessage;

  // Categories (for filter barrier selection).
  var _categories = <UtilityCategory>[];

  // The selected category for filter barriers.
  UtilityCategory? _selectedCategory;

  // Set to include/exclude isolated features in the trace.
  var _isIncludeIsolatedFeatures = true;

  // The Message to display on the banner.
  final String _message =
      'Tap on the map to add filter barriers, or run the trace directly without filter barriers.';

  @override
  void initState() {
    super.initState();
    // Set up authentication for the sample server.
    // Note: Never hardcode login information in a production application.
    // This is done solely for the sake of the sample.
    ArcGISEnvironment
        .authenticationManager
        .arcGISAuthenticationChallengeHandler = TokenChallengeHandler(
      'viewer01',
      'I68VGU^nMurF',
    );
  }

  @override
  void dispose() {
    ArcGISEnvironment
            .authenticationManager
            .arcGISAuthenticationChallengeHandler =
        null;
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        left: false,
        right: 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,
                    onTap: _onTap,
                  ),
                ),
                // Add the settings widget below the map view.
                _settingWidget(context),
              ],
            ),
            // Add a loading indicator while the map and utility network are loading.
            LoadingIndicator(
              visible: _loading,
              text: _loading ? _statusMessage : '',
            ),
            // Display a banner with instructions at the top.
            IgnorePointer(
              child: Container(
                padding: const EdgeInsets.all(5),
                color: Colors.white.withValues(alpha: 0.7),
                child: Row(
                  children: [
                    Expanded(
                      child: Text(
                        _statusMessage ?? '',
                        textAlign: TextAlign.center,
                        style: Theme.of(context).textTheme.labelMedium,
                        maxLines: 4,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  // Configurations for utility network tracing.
  Widget _settingWidget(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.fromLTRB(10, 10, 10, 0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        spacing: 4,
        children: [
          const Text('Choose Category for Filter Barriers:'),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            spacing: 4,
            children: [
              // The dropdown for categories.
              Expanded(
                child: DropdownButton(
                  isExpanded: true,
                  value: _selectedCategory,
                  hint: const Text('Select category'),
                  items: _categories.map((category) {
                    return DropdownMenuItem(
                      value: category,
                      child: Text(
                        category.name,
                        style: Theme.of(context).textTheme.bodyMedium,
                      ),
                    );
                  }).toList(),
                  onChanged: (value) {
                    setState(() {
                      _selectedCategory = value;
                    });
                  },
                ),
              ),
              // The button to start tracing.
              ElevatedButton(
                onPressed: _traceEnabled ? _onTrace : null,
                child: const Text('Trace'),
              ),
              // The button to reset the trace.
              ElevatedButton(
                onPressed: _resetEnabled ? _clear : null,
                child: const Text('Reset'),
              ),
            ],
          ),
          // The Switch for including isolated features.
          Row(
            spacing: 4,
            children: [
              Text(
                'Include isolated features',
                style: TextStyle(
                  color: (_selectedCategory == null)
                      ? Colors.grey
                      : Theme.of(context).textTheme.bodyMedium?.color,
                ),
              ),
              Switch(
                value: _isIncludeIsolatedFeatures,
                onChanged: (v) =>
                    setState(() => _isIncludeIsolatedFeatures = v),
              ),
              if (_isIncludeIsolatedFeatures)
                const Text('On')
              else
                const Text('Off'),
            ],
          ),
        ],
      ),
    );
  }

  /// Called when the map view is ready.
  Future<void> _onMapViewReady() async {
    setState(() {
      _loading = true;
      _statusMessage = 'Loading map...';
    });

    final map = ArcGISMap.withUri(
      Uri.parse(
        'https://sampleserver7.arcgisonline.com/portal/home/item.html?id=f439b4724bb54ac088a2c21eaf70da7b',
      ),
    );
    await map!.load();
    _mapViewController.arcGISMap = map;

    // Load the utility network.
    try {
      await _loadUtilityNetwork(map);
    } on Exception catch (e) {
      setState(() {
        _statusMessage = 'Error loading Utility Network: $e';
      });
    }
    setState(() => _loading = false);
  }

  /// Load the utility network from the service geodatabase.
  Future<void> _loadUtilityNetwork(ArcGISMap map) async {
    setState(() => _statusMessage = 'Loading Utility Network...');

    // Get and load the utility network from the map.
    _utilityNetwork = map.utilityNetworks.first;
    await _utilityNetwork.load();

    // Get the domain network and tier.
    final domainNetwork = _utilityNetwork.definition?.getDomainNetwork(
      'Pipeline',
    );
    final tier = domainNetwork?.getTier('Pipe Distribution System');
    // Get a trace configuration from the tier.
    _configuration = tier!.getDefaultTraceConfiguration();
    // Create a trace filter and set it on the configuration.
    _configuration!.filter = UtilityTraceFilter();

    // Get a default starting location.
    _startingLocationElement = _getStartingLocationElement();

    // Display starting locations.
    final graphicsOverlayStarting = GraphicsOverlay();
    _mapViewController.graphicsOverlays.add(graphicsOverlayStarting);
    final elementFeatures = await _utilityNetwork.getFeaturesForElements([
      _startingLocationElement,
    ]);
    final startingGeometry = elementFeatures.first.geometry! as ArcGISPoint;
    graphicsOverlayStarting.graphics.add(
      Graphic(geometry: startingGeometry, symbol: _startingPointSymbols),
    );

    // Add the graphics overlay for barriers.
    _mapViewController.graphicsOverlays.add(_graphicsOverlayBarriers);

    // Create the utility trace parameters.
    _traceParameters = UtilityTraceParameters(
      UtilityTraceType.isolation,
      startingLocations: [_startingLocationElement],
    );

    // Set viewpoint to starting location.
    _mapViewController.setViewpoint(
      Viewpoint.fromCenter(startingGeometry, scale: 3000),
    );

    // Load categories after network definition is available.
    _loadCategories();

    setState(() {
      _statusMessage = _message;
      _traceEnabled = true;
    });
  }

  // Get a default starting location for the trace.
  UtilityElement _getStartingLocationElement() {
    // Get a default starting location.
    final networkSource = _utilityNetwork.definition?.getNetworkSource(
      'Gas Device',
    );
    final assetGroup = networkSource?.getAssetGroup('Meter');
    final assetType = assetGroup?.getAssetType('Customer');
    final startingLocationElement = _utilityNetwork.createElementWithAssetType(
      assetType!,
      globalId: Guid.fromString('{98A06E95-70BE-43E7-91B7-E34C9D3CB9FF}')!,
    );
    return startingLocationElement;
  }

  /// Load the categories for the utility network.
  void _loadCategories() {
    final definition = _utilityNetwork.definition;
    final categoryList = definition?.categories;
    if (categoryList != null && categoryList.isNotEmpty) {
      setState(() {
        _categories = categoryList;
        _selectedCategory = _categories.first;
      });
    }
  }

  /// Handle tap events on the map.
  Future<void> _onTap(Offset screenPoint) async {
    if (_loading) return;
    final mapPoint = _mapViewController.screenToLocation(screen: screenPoint);

    // Identify a feature near the tap to create a starting element.
    final identifyResults = await _mapViewController.identifyLayers(
      screenPoint: screenPoint,
      tolerance: 10,
    );

    if (identifyResults.isEmpty || identifyResults.first.geoElements.isEmpty) {
      setState(() {
        _statusMessage =
            'No identified results/geoElements at the tapped location.';
      });
      return;
    }

    // Take first GeoElement.
    final geoElement = identifyResults.first.geoElements.first;
    // Create element from the identified feature.
    final utilityElement = _utilityNetwork.createElement(
      arcGISFeature: geoElement as ArcGISFeature,
    );

    // If the asset has terminals and we need a specific terminal, configure it here.
    if (utilityElement.networkSource.sourceType ==
        UtilityNetworkSourceType.junction) {
      // Select terminal for junction feature.
      final terminals =
          utilityElement.assetType.terminalConfiguration?.terminals;
      if (terminals != null && terminals.isNotEmpty) {
        if (terminals.length == 1) {
          utilityElement.terminal = terminals.first;
        } else {
          final selectedTerminal = await _showTerminalPicker(terminals);
          if (selectedTerminal != null) {
            utilityElement.terminal = selectedTerminal;
          } else {
            setState(() => _statusMessage = 'Terminal selection canceled.');
            return; // Abort adding barrier if no terminal chosen.
          }
        }
      }
    } else if (utilityElement.networkSource.sourceType ==
        UtilityNetworkSourceType.edge) {
      final line = GeometryEngine.removeZ(geoElement.geometry!) as Polyline;

      final fraction = GeometryEngine.fractionAlong(
        line: line,
        point: mapPoint!,
        tolerance: -1,
      );
      if (!fraction.isNaN) {
        utilityElement.fractionAlongEdge = fraction;
        setState(() {
          _statusMessage =
              'Edge element at distance ${fraction.toStringAsFixed(3)} along edge added to the filter barriers.';
        });
      }
    }

    // Add the utility element to the filter barriers of the trace parameters.
    _traceParameters.filterBarriers.add(utilityElement);

    // Add a graphic for the new utility element.
    final point = geoElement.geometry is ArcGISPoint
        ? geoElement.geometry! as ArcGISPoint
        : GeometryEngine.nearestCoordinate(
            geometry: geoElement.geometry!,
            point: mapPoint!,
          )?.coordinate;
    _graphicsOverlayBarriers.graphics.add(
      Graphic(
        geometry: point,
        symbol: _barrierPointSymbol,
        attributes: {
          'type': 'barrier',
          'index': _graphicsOverlayBarriers.graphics.length,
        },
      ),
    );

    setState(() {
      _statusMessage = _message;
      _resetEnabled = true;
    });
  }

  // Show a dialog for user to select one terminal when multiple are available.
  Future<UtilityTerminal?> _showTerminalPicker(
    List<UtilityTerminal> terminals,
  ) {
    return showDialog<UtilityTerminal>(
      context: context,
      builder: (context) => SimpleDialog(
        title: const Text('Select Terminal'),
        children:
            terminals
                .map(
                  (terminal) => SimpleDialogOption(
                    onPressed: () => Navigator.of(context).pop(terminal),
                    child: Text(terminal.name),
                  ),
                )
                .toList()
              ..add(
                SimpleDialogOption(
                  onPressed: () => Navigator.of(context).pop(),
                  child: const Text(
                    'Cancel',
                    style: TextStyle(color: Colors.redAccent),
                  ),
                ),
              ),
      ),
    );
  }

  // Perform the trace with the configured parameters.
  Future<void> _onTrace() async {
    final map = _mapViewController.arcGISMap;
    // Clear previous selection from the layers.
    map?.operationalLayers.whereType<FeatureLayer>().forEach(
      (layer) => layer.clearSelection(),
    );

    setState(() {
      _statusMessage = 'Tracing Utility Network';
      _traceEnabled = false;
    });

    // if no barriers are defined, use the category comparison.
    if (_traceParameters.barriers.isEmpty) {
      // Note: `UtilityNetworkAttributeComparison` or `UtilityCategoryComparison`
      // with `UtilityCategoryComparisonOperator.doesNotExist` can also be used.
      // These conditions can be joined with either `UtilityTraceOrCondition`
      // or `UtilityTraceAndCondition`.
      final utilityCategoryComparison = UtilityCategoryComparison.withCategory(
        _selectedCategory!,
        comparisonOperator: UtilityCategoryComparisonOperator.exists,
      );
      final filter = UtilityTraceFilter()..barriers = utilityCategoryComparison;
      // Add the filter barrier.
      _configuration!.filter = filter;
    }

    // Set the include isolated features property.
    _configuration!.includeIsolatedFeatures = _isIncludeIsolatedFeatures;

    // Build parameters for isolation trace
    _traceParameters.traceConfiguration = _configuration;

    // Get the trace result from trace.
    try {
      _statusMessage = '';
      final traceResults = await _utilityNetwork.trace(_traceParameters);

      final traceResult = traceResults.firstOrNull;
      if (traceResult != null && traceResult is UtilityElementTraceResult) {
        await _showTraceResult(traceResult);
      } else {
        _statusMessage = 'Trace completed with no output.';
      }
    } on Exception catch (e) {
      _statusMessage = 'Trace failed: $e.';
    }
    final statusMessage = _graphicsOverlayBarriers.graphics.isNotEmpty
        ? 'Trace with filter barriers completed.'
        : 'Trace with ${_selectedCategory?.name} category completed.';

    setState(() {
      _resetEnabled = true;
      _traceEnabled = true;
      _statusMessage = _statusMessage!.isNotEmpty
          ? _statusMessage
          : statusMessage;
    });
  }

  // Select and display all the features from the result.
  Future<void> _showTraceResult(UtilityElementTraceResult traceResult) async {
    final featureLayers =
        _mapViewController.arcGISMap?.operationalLayers
            .whereType<FeatureLayer>() ??
        [];

    if (traceResult.elements.isNotEmpty) {
      // Handle each element in the trace result.
      for (final featureLayer in featureLayers) {
        final elements = traceResult.elements.where(
          (element) =>
              element.networkSource.name ==
              featureLayer.featureTable?.tableName,
        );
        final features = await _utilityNetwork.getFeaturesForElements(
          List<UtilityElement>.from(elements),
        );
        featureLayer.selectFeatures(features);
      }
    } else {
      setState(() {
        _statusMessage = 'Trace completed with no output.';
      });
    }
  }

  void _clear() {
    _mapViewController.arcGISMap?.operationalLayers
        .whereType<FeatureLayer>()
        .forEach((layer) => layer.clearSelection());
    _traceParameters.filterBarriers.clear();
    _graphicsOverlayBarriers.graphics.clear();
    setState(() {
      _statusMessage =
          'Tap on the map to add filter barriers, or run the trace directly without filter barriers.';
      _resetEnabled = false;
    });
  }
}

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