Trace utility network

View on GitHub
Sample viewer app

Discover connected features in a utility network using connected, subnetwork, upstream, and downstream traces.

Trace utility network app

Use case

You can use a trace to visualize and validate the network topology of a utility network for quality assurance. Subnetwork traces are used for validating whether subnetworks, such as circuits or zones, are defined or edited appropriately.

How to use the sample

Tap on one or more features while 'Add starting locations' or 'Add barriers' is selected. When a junction feature is identified, you may be prompted to select a terminal. When an edge feature is identified, the distance from the tapped location to the beginning of the edge feature will be computed. Select the type of trace using the drop down menu. Click 'Trace' to initiate a trace on the network. Click 'Reset' to clear the trace parameters and start over.

How it works

  1. Create a MapView and add a DefaultMapViewOnTouchListener to listen for taps on the MapView.
  2. Create and load a ServiceGeodatabase with a feature service URL and get tables with their layer IDs.
  3. Create and load an ArcGISMap that contains FeatureLayer(s) that are part of a utility network.
  4. Create and load a UtilityNetwork using the utility network feature service URL and the map created in step 2.
  5. Add a GraphicsOverlay with symbology that distinguishes starting locations from barriers.
  6. Identify features on the map and add a Graphic that represents its purpose (starting location or barrier) at the tapped location.
  7. Create a UtilityElement for the identified feature.
  8. Determine the type of this element using its NetworkSource.sourceType property.
  9. 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.
  10. If an edge, set its FractionAlongLine property using GeometryEngine.fractionAlongEdge.
  11. Add this UtilityElement to a collection of starting locations or barriers.
  12. Create TraceParameters with the selected trace type along with the collected starting locations and barriers (if applicable).
  13. Set the TraceParameters.traceConfiguration with the utility tier's TraceConfiguration property.
  14. Run a UtilityNetwork.traceAsync(...) with the specified parameters.
  15. For every FeatureLayer in the map, select the features using the UtilityElement.objectId from the filtered list of UtilityElementTraceResult.elements.

Relevant API

  • FractionAlong
  • ServiceGeodatabase
  • UtilityAssetType
  • UtilityDomainNetwork
  • UtilityElement
  • UtilityElementTraceResult
  • UtilityNetwork
  • UtilityNetworkDefinition
  • UtilityNetworkSource
  • UtilityTerminal
  • UtilityTier
  • UtilityTraceConfiguration
  • UtilityTraceParameters
  • UtilityTraceResult
  • UtilityTraceType
  • UtilityTraversability

About the data

The Naperville electrical network feature service hosted on ArcGIS Online contains a utility network used to run the subnetwork-based trace shown in this sample.

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

condition barriers, downstream trace, network analysis, subnetwork trace, trace configuration, traversability, upstream trace, utility network, validate consistency

Sample Code

MainActivity.kt
Use dark colors for code blocks
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      
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
/*
 *  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.
 */

package com.esri.arcgisruntime.sample.traceutilitynetwork

import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.widget.*
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.esri.arcgisruntime.ArcGISRuntimeEnvironment
import com.esri.arcgisruntime.data.ArcGISFeature
import com.esri.arcgisruntime.data.QueryParameters
import com.esri.arcgisruntime.data.ServiceGeodatabase
import com.esri.arcgisruntime.geometry.*
import com.esri.arcgisruntime.layers.FeatureLayer
import com.esri.arcgisruntime.loadable.LoadStatus
import com.esri.arcgisruntime.mapping.ArcGISMap
import com.esri.arcgisruntime.mapping.BasemapStyle
import com.esri.arcgisruntime.mapping.Viewpoint
import com.esri.arcgisruntime.mapping.view.DefaultMapViewOnTouchListener
import com.esri.arcgisruntime.mapping.view.Graphic
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay
import com.esri.arcgisruntime.mapping.view.MapView
import com.esri.arcgisruntime.sample.traceutilitynetwork.databinding.ActivityMainBinding
import com.esri.arcgisruntime.security.UserCredential
import com.esri.arcgisruntime.symbology.SimpleLineSymbol
import com.esri.arcgisruntime.symbology.SimpleMarkerSymbol
import com.esri.arcgisruntime.symbology.UniqueValueRenderer
import com.esri.arcgisruntime.utilitynetworks.*
import kotlin.math.roundToInt

class MainActivity : AppCompatActivity() {

    private val activityMainBinding by lazy {
        ActivityMainBinding.inflate(layoutInflater)
    }

    private val mapView: MapView by lazy {
        activityMainBinding.mapView
    }

    private val progressIndicator: ProgressBar by lazy {
        activityMainBinding.progressIndicator
    }

    private val startingLocationsRadioButton: RadioButton by lazy {
        activityMainBinding.controlsLayout.startingLocationsRadioButton
    }

    private val statusTextView: TextView by lazy {
        activityMainBinding.controlsLayout.statusTextView
    }

    private val resetButton: Button by lazy {
        activityMainBinding.controlsLayout.resetButton
    }

    private val traceButton: Button by lazy {
        activityMainBinding.controlsLayout.traceButton
    }

    private val traceTypeSpinner: Spinner by lazy {
        activityMainBinding.controlsLayout.traceTypeSpinner
    }

    private var mediumVoltageTier: UtilityTier? = null
    private val graphicsOverlay: GraphicsOverlay by lazy { GraphicsOverlay() }

    private val featureServiceUrl =
        "https://sampleserver7.arcgisonline.com/server/rest/services/UtilityNetwork/NapervilleElectric/FeatureServer"

    private val serviceGeodatabase by lazy {
        ServiceGeodatabase(featureServiceUrl).apply {
            // define user credentials for authenticating with the service
            // NOTE: a licensed user is required to perform utility network operations
            credential = UserCredential("viewer01", "I68VGU^nMurF")
        }
    }
    private val utilityNetwork: UtilityNetwork by lazy {
        UtilityNetwork(featureServiceUrl).apply {
            // define user credentials for authenticating with the service
            // NOTE: a licensed user is required to perform utility network operations
            credential = UserCredential("viewer01", "I68VGU^nMurF")
        }
    }

    // create lists for starting locations and barriers
    private val utilityElementStartingLocations: MutableList<UtilityElement> by lazy { ArrayList() }
    private val utilityElementBarriers: MutableList<UtilityElement> by lazy { ArrayList() }

    // create symbols for the starting point and barriers
    private val startingPointSymbol: SimpleMarkerSymbol by lazy {
        SimpleMarkerSymbol(SimpleMarkerSymbol.Style.CROSS, Color.GREEN, 25f)
    }
    private val barrierPointSymbol: SimpleMarkerSymbol by lazy {
        SimpleMarkerSymbol(SimpleMarkerSymbol.Style.X, Color.RED, 25f)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(activityMainBinding.root)

        // authentication with an API key or named user is required to access basemaps and other
        // location services
        ArcGISRuntimeEnvironment.setApiKey(BuildConfig.API_KEY)

        serviceGeodatabase.loadAsync()
        serviceGeodatabase.addDoneLoadingListener {
            serviceGeodatabase.loadStatus
            // create electrical distribution line layer from the service geodatabase
        val electricalDistributionFeatureLayer =
            FeatureLayer(serviceGeodatabase.getTable(3)).apply {
                // define a solid line for medium voltage lines
                val mediumVoltageValue = UniqueValueRenderer.UniqueValue(
                    "N/A",
                    "Medium voltage",
                    SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, Color.CYAN, 3f),
                    listOf(5)
                )
                // define a dashed line for low voltage lines
                val lowVoltageValue = UniqueValueRenderer.UniqueValue(
                    "N/A",
                    "Low voltage",
                    SimpleLineSymbol(SimpleLineSymbol.Style.DASH, Color.CYAN, 3f),
                    listOf(3)
                )
                // create and apply a solid light gray renderer
                renderer =
                    UniqueValueRenderer(
                        listOf("ASSETGROUP"),
                        listOf(mediumVoltageValue, lowVoltageValue),
                        "",
                        SimpleLineSymbol()
                    )
            }

        // create electrical device layerfrom the service geodatabase
        val electricalDeviceFeatureLayer =
            FeatureLayer(serviceGeodatabase.getTable(0))

        // setup the map view
        mapView.apply {
            // add a map with streets night vector basemap
            map = ArcGISMap(BasemapStyle.ARCGIS_STREETS_NIGHT).apply {
                operationalLayers.apply {
                    add(electricalDistributionFeatureLayer)
                    add(electricalDeviceFeatureLayer)
                }
            // add the utility network to the map
                    utilityNetworks.add(utilityNetwork)
                }

            // set the viewpoint to a section in the southeast of the network
            setViewpointAsync(
                Viewpoint(
                    Envelope(
                        -9813547.35557238,
                        5129980.36635111,
                        -9813185.0602376,
                        5130215.41254146,
                        SpatialReferences.getWebMercator()
                    )
                )
            )

            // set the selection color for features in the map view
            selectionProperties.color = Color.YELLOW

            // add a graphics overlay
            graphicsOverlays.add(graphicsOverlay)

            // handle taps on the map view
            onTouchListener = object : DefaultMapViewOnTouchListener(applicationContext, mapView) {
                override fun onSingleTapConfirmed(e: MotionEvent): Boolean {
                    // only pass taps to identify nearest utility element once the utility network has loaded
                    if (utilityNetwork.loadStatus == LoadStatus.LOADED) {
                        identifyNearestUtilityElement(
                            android.graphics.Point(e.x.roundToInt(), e.y.roundToInt())
                        )
                        return true
                    }
                    return false
                }
            }
        }

        // load the utility network
        utilityNetwork.addDoneLoadingListener {
            if (utilityNetwork.loadStatus == LoadStatus.LOADED) {
                // update the status text
                statusTextView.text = getString(R.string.click_to_add_points)

                // get the utility tier used for traces in this network, in this case "Medium Voltage Radial"
                val domainNetwork =
                    utilityNetwork.definition.getDomainNetwork("ElectricDistribution")
                mediumVoltageTier = domainNetwork.getTier("Medium Voltage Radial")

            } else {
                reportError("Error loading utility network: " + utilityNetwork.loadError.cause?.message)
            }
        }
        utilityNetwork.loadAsync()}

        // add all utility trace types to the trace type spinner as strings
        traceTypeSpinner.adapter = ArrayAdapter(
            applicationContext,
            android.R.layout.simple_spinner_item,
            arrayOf("CONNECTED", "SUBNETWORK", "UPSTREAM", "DOWNSTREAM")
        )


    }

    /**
     * Uses the tapped point to identify any utility elements in the utility network at the tapped
     * location. Based on the selection mode, the tapped utility element is added either to the
     * starting locations or barriers for the trace parameters. An appropriate graphic is created at
     * the tapped location to mark the element as either a starting location or barrier.
     *
     * @param screenPoint used to identify utility elements in the utility network
     */
    private fun identifyNearestUtilityElement(screenPoint: android.graphics.Point) {
        // get the clicked map point
        val mapPoint = mapView.screenToLocation(screenPoint)
        // identify the feature to be used
        val identifyLayerResultFuture = mapView.identifyLayersAsync(screenPoint, 10.0, false)
        identifyLayerResultFuture.addDoneListener {
            // get the result of the query
            try {
                val identifyResults = identifyLayerResultFuture.get()
                // if the identify returns a result, retrieve the geoelement as an ArcGISFeature
                (identifyResults.getOrNull(0)?.elements?.get(0) as? ArcGISFeature)?.let { identifiedFeature ->
                    // get the network source of the identified feature
                    val utilityNetworkSource =
                        utilityNetwork.definition.getNetworkSource(identifiedFeature.featureTable.tableName)
                    // check if the network source is a junction or an edge
                    when (utilityNetworkSource.sourceType) {
                        UtilityNetworkSource.Type.JUNCTION -> {
                            // create a utility element with the identified feature
                            createUtilityElement(identifiedFeature, utilityNetworkSource)
                        }
                        UtilityNetworkSource.Type.EDGE -> {
                            //  create a utility element with the identified feature
                            utilityNetwork.createElement(identifiedFeature, null).apply {
                                // calculate how far the clicked location is along the edge feature
                                fractionAlongEdge = GeometryEngine.fractionAlong(
                                    GeometryEngine.removeZ(identifiedFeature.geometry) as Polyline,
                                    mapPoint,
                                    -1.0
                                )
                                // set the trace location graphic to the nearest coordinate to the tapped point
                                addUtilityElementToMap(identifiedFeature, mapPoint, this)
                            }.also {
                                // update the status label text
                                statusTextView.text =
                                    getString(R.string.fraction_message, it.fractionAlongEdge)
                            }
                        }
                        else -> error("Unexpected utility network source type!")
                    }
                }
            } catch (e: Exception) {
                reportError("Error getting identify results: " + e.message)
            }
        }
    }

    /**
     * Add utility element to either the starting locations or barriers list and add a graphic
     * representing it to the graphics overlay.
     *
     * @param identifiedFeature the feature identified by a tap
     * @param mapPoint the map location of the tap
     * @param utilityElement to be added to the map
     */
    private fun addUtilityElementToMap(
        identifiedFeature: ArcGISFeature,
        mapPoint: Point,
        utilityElement: UtilityElement
    ) {
        graphicsOverlay.graphics.add(
            Graphic(
                GeometryEngine.nearestCoordinate(
                    identifiedFeature.geometry,
                    mapPoint
                ).coordinate
            ).apply {
                // add the element to the appropriate list (starting locations or barriers), and add the
                // appropriate symbol to the graphic
                symbol = if (startingLocationsRadioButton.isChecked) {
                    utilityElementStartingLocations.add(utilityElement)
                    startingPointSymbol
                } else {
                    utilityElementBarriers.add(utilityElement)
                    barrierPointSymbol
                }
            })
    }

    /**
     * Uses a UtilityNetworkSource to create a UtilityElement object out of an ArcGISFeature.
     *
     * @param identifiedFeature an ArcGISFeature object that will be used to create a UtilityElement
     * @param networkSource     the UtilityNetworkSource to which the created UtilityElement is associated
     */
    private fun createUtilityElement(
        identifiedFeature: ArcGISFeature,
        networkSource: UtilityNetworkSource
    ) {
        // find the code matching the asset group name in the feature's attributes
        val assetGroupCode =
            identifiedFeature.attributes[identifiedFeature.featureTable.subtypeField] as Int

        // find the network source's asset group with the matching code
        networkSource.assetGroups.filter { it.code == assetGroupCode }[0].assetTypes
            // find the asset group type code matching the feature's asset type code
            .filter { it.code == identifiedFeature.attributes["assettype"].toString().toInt() }[0]
            .let { utilityAssetType ->
                // get the list of terminals for the feature
                val terminals = utilityAssetType.terminalConfiguration.terminals

                // if there is only one terminal, use it to create a utility element
                when (terminals.size) {
                    1 -> {
                        // create a utility element
                        utilityNetwork.createElement(identifiedFeature, terminals[0]).also {
                            // add the utility element to the map
                            addUtilityElementToMap(
                                identifiedFeature,
                                identifiedFeature.geometry as Point,
                                it
                            )
                        }
                    }
                    // if there is more than one terminal, prompt the user to select one
                    else -> {
                        // get a list of terminal names from the terminals
                        val terminalNames =
                            utilityAssetType.terminalConfiguration.terminals.map { it.name }
                        AlertDialog.Builder(this).apply {
                            setTitle("Select utility terminal:")
                            setItems(terminalNames.toTypedArray()) { _, which ->
                                // create a utility element
                                utilityNetwork.createElement(identifiedFeature, terminals[which])
                                    .also {
                                        // add the utility element to the map
                                        addUtilityElementToMap(
                                            identifiedFeature,
                                            identifiedFeature.geometry as Point,
                                            it
                                        )
                                        // show the utility element name in the UI
                                        showTerminalNameInStatusLabel(it.terminal)
                                    }
                            }
                        }.show()
                    }
                }

            }
    }

    /**
     * Shows the name of a UtilityTerminal in the status label in the UI.
     *
     * @param terminal to show information about
     */
    private fun showTerminalNameInStatusLabel(terminal: UtilityTerminal) {
        statusTextView.text =
            getString(
                R.string.terminal_name,
                if (!terminal.name.isNullOrEmpty()) terminal.name else "default"
            )
    }

    /**
     * Uses the elements selected as starting locations and (optionally) barriers to perform a connected trace,
     * then selects all connected elements found in the trace to highlight them.
     */
    fun traceUtilityNetwork(view: View) {
        // check that the utility trace parameters are valid
        if (utilityElementStartingLocations.isEmpty()) {
            reportError("No starting locations provided for trace.")
            return
        }

        // show the progress indicator and update the status text
        progressIndicator.visibility = View.VISIBLE
        statusTextView.text = getString(R.string.find_connected_features_message)
        disableButtons()

        // create utility trace parameters for the given trace type
        val traceType = UtilityTraceType.valueOf(traceTypeSpinner.selectedItem.toString())
        // create trace parameters
        val traceParameters =
            UtilityTraceParameters(traceType, utilityElementStartingLocations).apply {
                // if any barriers have been created, add them to the parameters
                barriers.addAll(utilityElementBarriers)
                // set the trace configuration using the tier from the utility domain network
                traceConfiguration = mediumVoltageTier?.traceConfiguration
            }
        // run the utility trace and get the results
        val utilityTraceResultsFuture = utilityNetwork.traceAsync(traceParameters)
        utilityTraceResultsFuture.addDoneListener {
            try {
                // get the utility trace result's first result as a utility element trace result
                (utilityTraceResultsFuture.get()[0] as? UtilityElementTraceResult)?.let { utilityElementTraceResult ->
                    // ensure the result is not empty
                    if (utilityElementTraceResult.elements.isNotEmpty()) {
                        // iterate through the map's feature layers
                        mapView.map.operationalLayers.filterIsInstance<FeatureLayer>()
                            .forEach { featureLayer ->

                                // clear previous selection
                                featureLayer.clearSelection()

                                // create query parameters to find features who's network source name matches the layer's feature table name
                                with(QueryParameters()) {
                                    utilityElementTraceResult.elements.filter { it.networkSource.name == featureLayer.featureTable.tableName }
                                        .forEach { utilityElement ->
                                            this.objectIds.add(utilityElement.objectId)
                                        }

                                    // select features that match the query
                                    featureLayer.selectFeaturesAsync(
                                        this,
                                        FeatureLayer.SelectionMode.NEW
                                    )
                                        .addDoneListener {
                                            // when done, update status text, enable buttons and hide progress indicator
                                            statusTextView.text =
                                                getString(R.string.trace_completed)
                                            enableButtons()
                                            progressIndicator.visibility = View.GONE
                                        }
                                }
                            }
                    } else {
                        Toast.makeText(this, "No elements in trace result", Toast.LENGTH_LONG)
                            .show()
                        progressIndicator.visibility = View.GONE
                      enableButtons()
                    }
                }
            } catch (e: Exception) {
                statusTextView.text = getString(R.string.failed_message)
                progressIndicator.visibility = View.GONE
                enableButtons()
                reportError("Error running connected trace: " + e.message)
            }
        }
    }

    /**
     * Enables both buttons.
     */
    private fun enableButtons() {
        // enable the UI
        resetButton.isEnabled = true
        traceButton.isEnabled = true
    }

    /**
     * Disables both buttons.
     */
    private fun disableButtons() {
        // enable the UI
        resetButton.isEnabled = false
        traceButton.isEnabled = false
    }

    /**
     * Restores the sample to the startup-state by resetting the status text, hiding the progress indicator, clearing
     * the trace parameters, de-selecting all features and removing any graphics
     */
    fun reset(view: View) {
        statusTextView.text = getString(R.string.add_utility_element)
        progressIndicator.visibility = View.GONE

        // clear the utility trace parameters
        utilityElementStartingLocations.clear()
        utilityElementBarriers.clear()
        // clear any selected features in the map's feature layers
        mapView.map.operationalLayers.filterIsInstance<FeatureLayer>().forEach {
            it.clearSelection()
        }
        // clear the graphics overlay
        graphicsOverlay.graphics.clear()
        // enable the trace button
        traceButton.isEnabled = true
    }

    /**
     * Report the given error to the user by toast and log.
     *
     * @param error as a string
     */
    private fun reportError(error: String) {
        Toast.makeText(this, error, Toast.LENGTH_LONG).show()
        Log.e(this::class.java.simpleName, error)
    }

    override fun onPause() {
        mapView.pause()
        super.onPause()
    }

    override fun onResume() {
        super.onResume()
        mapView.resume()
    }

    override fun onDestroy() {
        mapView.dispose()
        super.onDestroy()
    }
}

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