Skip to content
View on GitHub

Create graphics for utility associations in a utility network.

Image of show utility associations

Use case

Visualizing utility associations can help you to better understand trace results and the topology of your utility network. For example, connectivity associations allow you to model connectivity between two junctions that don't have geometric coincidence (are not in the same location); structural attachment associations allow you to model equipment that may be attached to structures; and containment associations allow you to model features contained within other features.

How to use the sample

Pan and zoom around the map. Observe graphics that show utility associations between junctions.

How it works

  1. Create and load an ArcGISMap with a web map item URL that contains a UtilityNetwork.
  2. Get and load the first UtilityNetwork from the web map.
  3. Create a GraphicsOverlay for the utility associations.
  4. Add an event handler for the onViewpointChanged event of the ArcGISMapViewController.
  5. When the sample starts and every time the viewpoint changes, do the following steps.
  6. Get the geometry of the mapview's extent using getCurrentViewpoint(ViewpointType.boundingGeometry)?.targetGeometry.extent.
  7. Get the associations that are within the current extent using getAssociationsWithEnvelope(extent).
  8. Get the UtilityAssociationType for each association.
  9. Create a Graphic using the Geometry property of the association and a preferred symbol.
  10. Add the graphic to the graphics overlay.

Relevant API

  • GraphicsOverlay
  • UtilityAssociation
  • UtilityAssociationType
  • UtilityNetwork

About the data

The Naperville Electric Map web map contains a utility network used to run the subnetwork-based trace 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

associating, association, attachment, connectivity, containment, relationships

Sample Code

show_utility_associations.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
// 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 'dart:async';

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 ShowUtilityAssociations extends StatefulWidget {
  const ShowUtilityAssociations({super.key});

  @override
  State<ShowUtilityAssociations> createState() =>
      _ShowUtilityAssociationsState();
}

class _ShowUtilityAssociationsState extends State<ShowUtilityAssociations>
    with SampleStateSupport {
  // Create a controller for the map view.
  final _mapViewController = ArcGISMapView.createController();

  // The utility network.
  late UtilityNetwork _utilityNetwork;

  // A graphics overlay to display the utility associations.
  final _associationsOverlay = GraphicsOverlay();

  // A symbol for attachment associations.
  final _attachmentSymbol = SimpleLineSymbol(
    style: SimpleLineSymbolStyle.dot,
    color: Colors.green,
    width: 5,
  );

  // A symbol for connectivity associations.
  final _connectivitySymbol = SimpleLineSymbol(
    style: SimpleLineSymbolStyle.dot,
    color: Colors.red,
    width: 5,
  );

  // A subscription to the viewpoint changed event.
  StreamSubscription<void>? _viewpointChangedSubscription;

  // A flag for when the map view is ready and controls can be used.
  var _ready = false;

  @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() {
    // Remove the TokenChallengeHandler and erase any credentials that were generated.
    ArcGISEnvironment
            .authenticationManager
            .arcGISAuthenticationChallengeHandler =
        null;
    ArcGISEnvironment.authenticationManager.arcGISCredentialStore.removeAll();

    _viewpointChangedSubscription?.cancel().ignore();

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          // Add a map view to the widget tree and set a controller.
          ArcGISMapView(
            controllerProvider: () => _mapViewController,
            onMapViewReady: onMapViewReady,
          ),
          // Add a legend for the association types.
          SafeArea(
            child: Align(
              alignment: Alignment.topLeft,
              child: Container(
                margin: const EdgeInsets.all(20),
                decoration: BoxDecoration(
                  color: Colors.white.withValues(alpha: 0.9),
                  borderRadius: BorderRadius.circular(10),
                ),
                child: Padding(
                  padding: const EdgeInsets.all(10),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    spacing: 5,
                    children: [
                      const Text('Utility association types'),
                      Container(
                        decoration: BoxDecoration(
                          border: Border.all(color: Colors.grey),
                        ),
                        padding: const EdgeInsets.fromLTRB(5, 5, 50, 5),
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Row(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                SwatchImage(symbol: _attachmentSymbol),
                                const Text('Attachment'),
                              ],
                            ),
                            Row(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                SwatchImage(symbol: _connectivitySymbol),
                                const Text('Connectivity'),
                              ],
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ),
          // Display a progress indicator and prevent interaction until state is ready.
          LoadingIndicator(visible: !_ready),
        ],
      ),
    );
  }

  Future<void> onMapViewReady() async {
    // Create a map from a PortalItem that contains the Naperville Electric Map.
    final portalItem = PortalItem.withPortalAndItemId(
      portal: Portal(
        Uri.parse('https://sampleserver7.arcgisonline.com/portal/'),
        connection: PortalConnection.authenticated,
      ),
      itemId: 'be0e4637620a453584118107931f718b',
    );
    final map = ArcGISMap.withItem(portalItem);

    // Load the map to make the utility network available.
    await map.load();

    // Set the initial viewpoint in the utility network area.
    map.initialViewpoint = Viewpoint.withLatLongScale(
      latitude: 41.8057655,
      longitude: -88.1489692,
      scale: 70.5310735,
    );

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

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

    // Prepare the associations graphics overlay, with symbols for each type.
    _associationsOverlay.renderer = UniqueValueRenderer(
      fieldNames: ['AssociationType'],
      uniqueValues: [
        UniqueValue(
          description: 'Attachment',
          symbol: _attachmentSymbol,
          values: [UtilityAssociationType.attachment.name],
        ),
        UniqueValue(
          description: 'Connectivity',
          symbol: _connectivitySymbol,
          values: [UtilityAssociationType.connectivity.name],
        ),
      ],
    );
    _mapViewController.graphicsOverlays.add(_associationsOverlay);

    // Add a handler for viewpoint changes to update the associations.
    _viewpointChangedSubscription = _mapViewController.onViewpointChanged
        .listen((_) => addAssociationGraphics());
    await addAssociationGraphics();

    // Set the ready state variable to true to enable the sample UI.
    setState(() => _ready = true);
  }

  Future<void> addAssociationGraphics() async {
    // Get the current scale.
    final scale =
        _mapViewController
            .getCurrentViewpoint(ViewpointType.centerAndScale)
            ?.targetScale ??
        double.infinity;

    // Don't add graphics if the scale is too large.
    const maxScale = 2000;
    if (scale > maxScale) return;

    // Get the current extent.
    final extent = _mapViewController
        .getCurrentViewpoint(ViewpointType.boundingGeometry)
        ?.targetGeometry
        .extent;
    if (extent == null) return;

    // Find the associations in the current extent.
    final associations = await _utilityNetwork.getAssociationsWithEnvelope(
      extent,
    );

    // Filter out associations that are already being displayed.
    final existingAssociations = _associationsOverlay.graphics
        .map((graphic) => graphic.attributes['GlobalId'])
        .whereType<Guid>()
        .toSet();
    final newAssociations = associations.where(
      (association) => !existingAssociations.contains(association.globalId),
    );

    // Add graphics for the new associations.
    _associationsOverlay.graphics.addAll(
      newAssociations.map(
        (association) => Graphic(
          geometry: association.geometry,
          attributes: {
            'GlobalId': association.globalId,
            'AssociationType': association.associationType.name,
          },
        ),
      ),
    );
  }
}

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