Create graphics for utility associations in a utility network.

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
- Create and load a
Mapwith a web map item URL that contains aUtilityNetwork. - Get and load the first
UtilityNetworkfrom the web map. - Create a
GraphicsOverlayfor the utility associations. - Add connection for the
ViewpointChangedsignal of theMapView. - When the sample starts and every time the viewpoint changes, do the following steps.
- Get the geometry of the mapview’s extent using
currentViewpoint(ViewpointType::BoundingGeometry).targetGeometry.extent. - Get the associations that are within the current extent using
associationsAsync(extent). - Get the
UtilityAssociationTypefor each association. - Create a
Graphicusing theGeometryproperty of the association and a preferred symbol. - Add the graphic to the graphics overlay.
Relevant API
- GraphicsOverlay
- ServiceGeodatabase
- UtilityAssociation
- UtilityAssociationType
- UtilityNetwork
About the data
The Naperville electrical web map contains a utility network used to run the subnetwork-based trace 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.
Credentials:
- Username: viewer01
- Password: I68VGU^nMurF
Tags
associating, association, attachment, connectivity, containment, relationships
Sample Code
// [WriteFile Name=DisplayUtilityAssociations, Category=UtilityNetwork]// [Legal]// 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.// [Legal]
#ifdef PCH_BUILD#include "pch.hpp"#endif // PCH_BUILD
// sample headers#include "DisplayUtilityAssociations.h"#include "SymbolImageProvider.h"
// ArcGIS Maps SDK headers#include "ArcGISRuntimeEnvironment.h"#include "Authentication/AuthenticationManager.h"#include "Authentication/ArcGISAuthenticationChallenge.h"#include "Authentication/TokenCredential.h"#include "ArcGISFeatureTable.h"#include "AttributeListModel.h"#include "Envelope.h"#include "ErrorException.h"#include "FeatureLayer.h"#include "Graphic.h"#include "GraphicListModel.h"#include "GraphicsOverlay.h"#include "GraphicsOverlayListModel.h"#include "LayerListModel.h"#include "Map.h"#include "MapQuickView.h"#include "MapTypes.h"#include "Point.h"#include "SimpleLineSymbol.h"#include "SpatialReference.h"#include "SymbolTypes.h"#include "UniqueValue.h"#include "UniqueValueRenderer.h"#include "UtilityAssociation.h"#include "UtilityNetwork.h"#include "UtilityNetworkDefinition.h"#include "UtilityNetworkListModel.h"#include "UtilityNetworkTypes.h"#include "Viewpoint.h"
// Qt headers#include <QFuture>#include <QImage>#include <QList>#include <QQmlContext>#include <QUuid>
using namespace Esri::ArcGISRuntime;using namespace Esri::ArcGISRuntime::Authentication;
namespace{const int maxScale = 2000;constexpr int targetScale = 50;}
DisplayUtilityAssociations::DisplayUtilityAssociations(QObject* parent /* = nullptr */): ArcGISAuthenticationChallengeHandler(parent), m_map(new Map(QUrl("https://sampleserver7.arcgisonline.com/portal/home/item.html?id=be0e4637620a453584118107931f718b"), this)), m_associationsOverlay(new GraphicsOverlay(this)), m_attachmentSymbol(new SimpleLineSymbol(SimpleLineSymbolStyle::Dot, Qt::green, 5, this)), m_connectivitySymbol(new SimpleLineSymbol(SimpleLineSymbolStyle::Dot, Qt::red, 5, this)){ ArcGISRuntimeEnvironment::authenticationManager()->setArcGISAuthenticationChallengeHandler(this);
connect(m_map, &Map::doneLoading, this, [this](const Error& error) { if (!error.isEmpty() || m_map->utilityNetworks()->isEmpty()) { return; }
m_utilityNetwork = m_map->utilityNetworks()->first(); m_utilityNetwork->load(); connectSignals(); });}
void DisplayUtilityAssociations::handleArcGISAuthenticationChallenge(ArcGISAuthenticationChallenge* challenge){ TokenCredential::createWithChallengeAsync(challenge, "viewer01", "I68VGU^nMurF", {}, this).then(this, [challenge](TokenCredential* tokenCredential) { challenge->continueWithCredential(tokenCredential); }).onFailed(this, [challenge](const ErrorException& e) { challenge->continueWithError(e.error()); });}
void DisplayUtilityAssociations::addAssociations(){ // check if current viewpoint is outside the max scale if(m_mapView->currentViewpoint(ViewpointType::CenterAndScale).targetScale() >= maxScale) return;
// check if current viewpoint has a valid extent const Envelope extent = m_mapView->currentViewpoint(ViewpointType::BoundingGeometry).targetGeometry().extent(); if (!extent.isValid()) { qDebug("Extent not valid"); return; }
// get all the associations in the extent of the viewpoint m_utilityNetwork->associationsAsync(extent).then(this, [this](const QList<UtilityAssociation*>& associations) { const GraphicListModel* graphics = m_associationsOverlay->graphics();
for (UtilityAssociation* association : associations) { // check if the graphics overlay already contains the association const bool uniqueGraphic = std::none_of(graphics->begin(), graphics->end(), [association](const Graphic* graphic) { const AttributeListModel* attributes = graphic->attributes(); return attributes->containsAttribute("GlobalId") && qvariant_cast<QUuid>((*graphic->attributes())["GlobalId"]) == association->globalId(); });
if (uniqueGraphic) { // add a graphic for the association QVariantMap graphicAttributes; graphicAttributes["GlobalId"] = association->globalId(); graphicAttributes["AssociationType"] = static_cast<int>(association->associationType()); Graphic* graphic = new Graphic(association->geometry(), graphicAttributes, this);
m_associationsOverlay->graphics()->append(graphic); } } });}
DisplayUtilityAssociations::~DisplayUtilityAssociations() = default;
void DisplayUtilityAssociations::init(){ // Register the map view for QML qmlRegisterType<MapQuickView>("Esri.Samples", 1, 0, "MapView"); qmlRegisterType<DisplayUtilityAssociations>("Esri.Samples", 1, 0, "DisplayUtilityAssociationsSample");}
MapQuickView* DisplayUtilityAssociations::mapView() const{ return m_mapView;}
// Set the view (created in QML)void DisplayUtilityAssociations::setMapView(MapQuickView* mapView){ if (!mapView || mapView == m_mapView) return;
m_mapView = mapView; m_mapView->setMap(m_map);
m_mapView->graphicsOverlays()->append(m_associationsOverlay);
// Get the image provider from the QML Engine QQmlEngine* engine = QQmlEngine::contextForObject(this)->engine(); m_symbolImageProvider = new SymbolImageProvider(); engine->addImageProvider(SymbolImageProvider::imageProviderId(), m_symbolImageProvider);
connect(m_mapView, &MapQuickView::navigatingChanged, this, [this]() { if (!m_mapView->isNavigating()) addAssociations(); });
emit mapViewChanged();}
void DisplayUtilityAssociations::connectSignals(){ connect(m_utilityNetwork, &UtilityNetwork::doneLoading, this, [this](const Error& error) { if (!error.isEmpty()) { qDebug() << error.message() << error.additionalMessage(); return; }
m_mapView->setViewpointAsync(Viewpoint(Point(-9812698.37297436, 5131928.33743317, SpatialReference::webMercator()), targetScale)).then(this, [this](bool succeeded) { if (!succeeded) return;
addAssociations(); });
// create a renderer for the associations UniqueValue* attachmentValue = new UniqueValue("Attachment", "", QVariantList{static_cast<int>(UtilityAssociationType::Attachment)}, m_attachmentSymbol, this); UniqueValue* connectivityValue = new UniqueValue("Connectivity", "", QVariantList{static_cast<int>(UtilityAssociationType::Connectivity)}, m_connectivitySymbol, this); UniqueValueRenderer* uniqueValueRenderer = new UniqueValueRenderer("", nullptr, QStringList{"AssociationType"}, QList<UniqueValue*>{attachmentValue, connectivityValue}, this); m_associationsOverlay->setRenderer(uniqueValueRenderer);
// populate the legend m_attachmentSymbol->createSwatchAsync().then(this, [this](const QImage& image) { if (!m_symbolImageProvider) return;
const QString imageId = QUuid().createUuid().toString(QUuid::WithoutBraces);
// add the image to the provider m_symbolImageProvider->addImage(imageId, image);
// update the URL with the unique id m_attachmentSymbolUrl = QString("image://%1/%2").arg(SymbolImageProvider::imageProviderId(), imageId);
// emit the signal to trigger the QML Image to update emit attachmentSymbolUrlChanged(); });
m_connectivitySymbol->createSwatchAsync().then(this, [this](const QImage& image) { if (!m_symbolImageProvider) return;
const QString imageId = QUuid().createUuid().toString(QUuid::WithoutBraces);
// add the image to the provider m_symbolImageProvider->addImage(imageId, image);
// update the URL with the unique id m_connectivitySymbolUrl = QString("image://%1/%2").arg(SymbolImageProvider::imageProviderId(), imageId);
// emit the signal to trigger the QML Image to update emit connectivitySymbolUrlChanged(); }); });}
QString DisplayUtilityAssociations::attachmentSymbolUrl() const{ return m_attachmentSymbolUrl;}
QString DisplayUtilityAssociations::connectivitySymbolUrl() const{ return m_connectivitySymbolUrl;}// [WriteFile Name=DisplayUtilityAssociations, Category=UtilityNetwork]// [Legal]// 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.// [Legal]
#ifndef DISPLAYUTILITYASSOCIATIONS_H#define DISPLAYUTILITYASSOCIATIONS_H
// ArcGIS Maps SDK headers#include "Authentication/ArcGISAuthenticationChallengeHandler.h"
namespace Esri::ArcGISRuntime{class GraphicsOverlay;class Map;class MapQuickView;class Symbol;class UtilityNetwork;}
namespace Esri::ArcGISRuntime::Authentication{class ArcGISAuthenticationChallenge;}
class SymbolImageProvider;
Q_MOC_INCLUDE("MapQuickView.h")
class DisplayUtilityAssociations : public Esri::ArcGISRuntime::Authentication::ArcGISAuthenticationChallengeHandler{ Q_OBJECT
Q_PROPERTY(Esri::ArcGISRuntime::MapQuickView* mapView READ mapView WRITE setMapView NOTIFY mapViewChanged) Q_PROPERTY(QString attachmentSymbolUrl READ attachmentSymbolUrl NOTIFY attachmentSymbolUrlChanged) Q_PROPERTY(QString connectivitySymbolUrl READ connectivitySymbolUrl NOTIFY connectivitySymbolUrlChanged)
public: explicit DisplayUtilityAssociations(QObject* parent = nullptr); ~DisplayUtilityAssociations();
static void init();
signals: void mapViewChanged(); void attachmentSymbolUrlChanged(); void connectivitySymbolUrlChanged();
private: Esri::ArcGISRuntime::MapQuickView* mapView() const; void setMapView(Esri::ArcGISRuntime::MapQuickView* mapView); void addAssociations(); QString attachmentSymbolUrl() const; QString connectivitySymbolUrl() const; void connectSignals();
void handleArcGISAuthenticationChallenge(Esri::ArcGISRuntime::Authentication::ArcGISAuthenticationChallenge* challenge) override;
Esri::ArcGISRuntime::Map* m_map = nullptr; Esri::ArcGISRuntime::MapQuickView* m_mapView = nullptr; Esri::ArcGISRuntime::GraphicsOverlay* m_associationsOverlay = nullptr; Esri::ArcGISRuntime::UtilityNetwork* m_utilityNetwork = nullptr; Esri::ArcGISRuntime::Symbol* m_attachmentSymbol = nullptr; Esri::ArcGISRuntime::Symbol* m_connectivitySymbol = nullptr; QString m_attachmentSymbolUrl = ""; QString m_connectivitySymbolUrl = ""; SymbolImageProvider* m_symbolImageProvider = nullptr;};
#endif // DISPLAYUTILITYASSOCIATIONS_H// [WriteFile Name=DisplayUtilityAssociations, Category=UtilityNetwork]// [Legal]// 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.// [Legal]
import QtQuickimport QtQuick.Controlsimport QtQuick.Layoutsimport Esri.Samples
Item { // add a mapView component MapView { id: view anchors.fill: parent
Component.onCompleted: { // Set the focus on MapView to initially enable keyboard navigation forceActiveFocus(); }
Control { background: Rectangle { border.color: "black" border.width: 1 } padding: 5 visible: model.attachmentSymbolUrl !== "" && model.connectivitySymbolUrl !== "" anchors { top: parent.top left: parent.left margins: 20 }
contentItem: GridLayout { id: grid columns: 2 anchors.horizontalCenter: parent.horizontalCenter Layout.fillWidth: true Label { text: "Utility association types" Layout.alignment: Qt.AlignHCenter Layout.fillWidth: true Layout.columnSpan: 2 }
Image { id: attachmentImage source: model.attachmentSymbolUrl fillMode: Image.PreserveAspectFit } Label { id: attachmentLabel text: "Attachment symbol" visible: model.attachmentSymbolUrl !== "" && model.connectivitySymbolUrl !== "" }
Image { id: connectivityImage source: model.connectivitySymbolUrl } Label { id: connectivityLabel text: "Connectivity symbol" visible: model.attachmentSymbolUrl !== "" && model.connectivitySymbolUrl !== "" } } } }
// Declare the C++ instance which creates the map etc. and supply the view DisplayUtilityAssociationsSample { id: model mapView: view }}// [Legal]// 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.// [Legal]
// sample headers#include "SymbolImageProvider.h"
// Qt headers#include <QQuickImageProvider>
SymbolImageProvider::SymbolImageProvider() : QQuickImageProvider(QQuickImageProvider::Image){}
// reimplemented function for QML to request Images from the providerQImage SymbolImageProvider::requestImage(const QString& id, QSize* size, const QSize& requestedSize){ Q_UNUSED(size) Q_UNUSED(requestedSize) return m_images[id];}
// helper to add images to the the providervoid SymbolImageProvider::addImage(const QString& id, const QImage& img){ m_images[id] = img;}
// static function to return the image provider idQString SymbolImageProvider::imageProviderId(){ return QStringLiteral("symbolimageprovider");}// [Legal]// 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.// [Legal]
// 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.
#ifndef SYMBOLIMAGEPROVIDER_H#define SYMBOLIMAGEPROVIDER_H
// Qt headers#include <QHash>#include <QImage>#include <QQuickImageProvider>
class SymbolImageProvider : public QQuickImageProvider{
public: SymbolImageProvider(); ~SymbolImageProvider() override = default;
public: QImage requestImage(const QString& id, QSize* size, const QSize& requestedSize) override; void addImage(const QString& id, const QImage& img); static QString imageProviderId();
private: QHash<QString, QImage> m_images;};
#endif // SYMBOLIMAGEPROVIDER_H// [Legal]// 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.// [Legal]
// sample headers#include "DisplayUtilityAssociations.h"
// ArcGIS Maps SDK headers#include "ArcGISRuntimeEnvironment.h"
// Qt headers#include <QDir>#include <QGuiApplication>#include <QQmlApplicationEngine>
// Platform specific headers#ifdef Q_OS_WIN#include <Windows.h>#endif
int main(int argc, char *argv[]){ Esri::ArcGISRuntime::ArcGISRuntimeEnvironment::setUseLegacyAuthentication(false); QGuiApplication app(argc, argv); app.setApplicationName(QString("DisplayUtilityAssociations"));
// Use of ArcGIS location services, such as basemap styles, geocoding, and routing services, // requires an access token. For more information see // https://links.esri.com/arcgis-runtime-security-auth.
// The following methods grant an access token:
// 1. User authentication: Grants a temporary access token associated with a user's ArcGIS account. // To generate a token, a user logs in to the app with an ArcGIS account that is part of an // organization in ArcGIS Online or ArcGIS Enterprise.
// 2. API key authentication: Get a long-lived access token that gives your application access to // ArcGIS location services. Go to the tutorial at https://links.esri.com/create-an-api-key. // Copy the API Key access token.
const QString accessToken = QString("");
if (accessToken.isEmpty()) { qWarning() << "Use of ArcGIS location services, such as the basemap styles service, requires" << "you to authenticate with an ArcGIS account or set the API Key property."; } else { Esri::ArcGISRuntime::ArcGISRuntimeEnvironment::setApiKey(accessToken); }
// Initialize the sample DisplayUtilityAssociations::init();
// Initialize application view QQmlApplicationEngine engine; // Add the import Path engine.addImportPath(QDir(QCoreApplication::applicationDirPath()).filePath("qml"));
#ifdef ARCGIS_RUNTIME_IMPORT_PATH_2 engine.addImportPath(ARCGIS_RUNTIME_IMPORT_PATH_2);#endif
// Set the source engine.load(QUrl("qrc:/Samples/UtilityNetwork/DisplayUtilityAssociations/main.qml"));
return app.exec();}// 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.
import QtQuick.Controlsimport Esri.Samples
ApplicationWindow { visible: true width: 800 height: 600
DisplayUtilityAssociations { anchors.fill: parent }}