Skip To Content ArcGIS for Developers Sign In Dashboard

ArcGIS Runtime SDK for .NET

Display utility associations

This code sample is available for these platforms:
View Sample on GitHub

Create graphics for utility associations in a utility network.

Image of display 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 a UtilityNetwork with a feature service URL.
  2. Add a FeatureLayer to the map for every UtilityNetworkSource of type Edge or Junction.
  3. Create a GraphicsOverlay for the utility associations.
  4. Add an event handler for the ViewpointChanged event of the MapView.
  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 GetAssociationsAsync(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 feature service in this sample represents an electric network in Naperville, Illinois, which contains a utility network used to run the subnetwork-based trace.

Tags

associating, association, attachment, connectivity, containment, relationships

Sample Code

<UserControl
    x:Class="ArcGISRuntime.UWP.Samples.DisplayUtilityAssociations.DisplayUtilityAssociations"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:esriUI="using:Esri.ArcGISRuntime.UI.Controls">
    <UserControl.Resources>
        <DataTemplate x:Key="AssociationLegendItemTemplate">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="30" />
                    <ColumnDefinition Width="*" />
                </Grid.ColumnDefinitions>
                <Image
                    Width="25"
                    Height="25"
                    Source="{Binding Value}" />
                <TextBlock Grid.Column="1" Text="{Binding Key}" />
            </Grid>
        </DataTemplate>
    </UserControl.Resources>
    <Grid>
        <esriUI:MapView x:Name="MyMapView" NavigationCompleted="OnNavigationCompleted" />
        <Border Style="{StaticResource BorderStyle}">
            <StackPanel>
                <TextBlock Margin="5" Text="Utility association types" />
                <ListView
                    x:Name="AssociationLegend"
                    Margin="5"
                    IsHitTestVisible="False"
                    ItemTemplate="{StaticResource AssociationLegendItemTemplate}" />
            </StackPanel>
        </Border>
    </Grid>
</UserControl>
// Copyright 2020 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.

using Esri.ArcGISRuntime;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Symbology;
using Esri.ArcGISRuntime.UI;
using Esri.ArcGISRuntime.UtilityNetworks;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using Windows.UI.Popups;
using Windows.UI.Xaml.Media;
using Symbol = Esri.ArcGISRuntime.Symbology.Symbol;

namespace ArcGISRuntime.UWP.Samples.DisplayUtilityAssociations
{
    [ArcGISRuntime.Samples.Shared.Attributes.Sample(
        name: "Display utility associations",
        category: "Utility network",
        description: "Create graphics for utility associations in a utility network.",
        instructions: "Pan and zoom around the map. Observe graphics that show utility associations between junctions.",
        tags: new[] { "associating", "association", "attachment", "connectivity", "containment", "relationships" })]
    public partial class DisplayUtilityAssociations
    {
        // Feature server for the utility network.
        private const string FeatureServerUrl = "https://sampleserver7.arcgisonline.com/arcgis/rest/services/UtilityNetwork/NapervilleElectric/FeatureServer";

        // This viewpoint shows several associations clearly in the utility network.
        private readonly Viewpoint InitialViewpoint = new Viewpoint(new MapPoint(-9812698.37297436, 5131928.33743317, SpatialReferences.WebMercator), 22d);

        // Max scale at which to create graphics for the associations.
        private const double _maxScale = 2000;

        // Overlay to hold graphics for all of the associations.
        private GraphicsOverlay _associationsOverlay;

        // Utility network that will be created from the feature server.
        private UtilityNetwork _utilityNetwork;

        public DisplayUtilityAssociations()
        {
            InitializeComponent();
            Initialize();
        }

        private async void Initialize()
        {
            try
            {
                // Create the utility network.
                _utilityNetwork = await UtilityNetwork.CreateAsync(new Uri(FeatureServerUrl));

                // Create the map.
                MyMapView.Map = new Map(Basemap.CreateTopographicVector());

                // Get all of the edges and junctions in the network.
                IEnumerable<UtilityNetworkSource> edges = _utilityNetwork.Definition.NetworkSources.Where(n => n.SourceType == UtilityNetworkSourceType.Edge);
                IEnumerable<UtilityNetworkSource> junctions = _utilityNetwork.Definition.NetworkSources.Where(n => n.SourceType == UtilityNetworkSourceType.Junction);

                // Add all edges that are not subnet lines to the map.
                foreach (UtilityNetworkSource source in edges)
                {
                    if (source.SourceUsageType != UtilityNetworkSourceUsageType.SubnetLine && source.FeatureTable != null)
                    {
                        MyMapView.Map.OperationalLayers.Add(new FeatureLayer(source.FeatureTable));
                    }
                }

                // Add all junctions to the map.
                foreach (UtilityNetworkSource source in junctions)
                {
                    if (source.FeatureTable != null)
                    {
                        MyMapView.Map.OperationalLayers.Add(new FeatureLayer(source.FeatureTable));
                    }
                }

                // Create a graphics overlay for associations.
                _associationsOverlay = new GraphicsOverlay();
                MyMapView.GraphicsOverlays.Add(_associationsOverlay);

                // Symbols for the associations.
                Symbol attachmentSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Dot, Color.Green, 5d);
                Symbol connectivitySymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Dot, Color.Red, 5d);

                // Create a renderer for the associations.
                var attachmentValue = new UniqueValue("Attachment", string.Empty, attachmentSymbol, UtilityAssociationType.Attachment.ToString());
                var connectivityValue = new UniqueValue("Connectivity", string.Empty, connectivitySymbol, UtilityAssociationType.Connectivity.ToString());
                _associationsOverlay.Renderer = new UniqueValueRenderer(new List<string> { "AssociationType" }, new List<UniqueValue> { attachmentValue, connectivityValue }, string.Empty, null);

                // Populate the legend in the UI.
                Dictionary<UtilityAssociationType, ImageSource> legend;
                legend = new Dictionary<UtilityAssociationType, ImageSource>();

                RuntimeImage attachmentSwatch = await attachmentSymbol.CreateSwatchAsync();
                legend[UtilityAssociationType.Attachment] = await attachmentSwatch?.ToImageSourceAsync();

                RuntimeImage connectSwatch = await connectivitySymbol.CreateSwatchAsync();
                legend[UtilityAssociationType.Connectivity] = await connectSwatch?.ToImageSourceAsync();

                AssociationLegend.ItemsSource = legend;

                // Set the starting viewpoint.
                await MyMapView.SetViewpointAsync(InitialViewpoint);

                // Add the associations in the starting viewpoint.
                AddAssociations();
            }
            catch (Exception ex)
            {
                await new MessageDialog(ex.Message, ex.GetType().Name).ShowAsync();
            }
        }

        private void OnNavigationCompleted(object sender, EventArgs e)
        {
            AddAssociations();
        }

        private async void AddAssociations()
        {
            try
            {
                // Check if the current viewpoint is outside of the max scale.
                if (MyMapView.GetCurrentViewpoint(ViewpointType.CenterAndScale)?.TargetScale >= _maxScale)
                {
                    return;
                }

                // Check if the current viewpoint has an extent.
                Envelope extent = MyMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry)?.TargetGeometry?.Extent;
                if (extent == null)
                {
                    return;
                }

                // Get all of the associations in extent of the viewpoint.
                IEnumerable<UtilityAssociation> associations = await _utilityNetwork.GetAssociationsAsync(extent);
                foreach (UtilityAssociation association in associations)
                {
                    // Check if the graphics overlay already contains the association.
                    if (_associationsOverlay.Graphics.Any(g => g.Attributes.ContainsKey("GlobalId") && (Guid)g.Attributes["GlobalId"] == association.GlobalId))
                    {
                        continue;
                    }

                    // Add a graphic for the association.
                    Graphic graphic = new Graphic(association.Geometry);
                    graphic.Attributes["GlobalId"] = association.GlobalId;
                    graphic.Attributes["AssociationType"] = association.AssociationType.ToString();
                    _associationsOverlay.Graphics.Add(graphic);
                }
            }

            // This is thrown when there are too many associations in the extent.
            catch (TooManyAssociationsException)
            {
            }
            catch (Exception ex)
            {
                await new MessageDialog(ex.Message, ex.GetType().Name).ShowAsync();
            }
        }
    }
}