Display data from an ArcGIS stream service using a dynamic entity layer.

Use case
A stream service is a type of service provided by ArcGIS Velocity and GeoEvent Server that allows clients to receive a stream of data observations via a web socket. ArcGIS Maps SDK for Qt allows you to connect to a stream service and manage the information as dynamic entities and display them in a dynamic entity layer. Displaying information from feeds such as a stream service is important in applications like dashboards where users need to visualize and track updates of real-world objects in real-time.
Use ArcGISStreamService to manage the connection to the stream service and purge options to manage how much data is stored and maintained by the application. The dynamic entity layer will display the latest received observation, and you can set track display properties to determine how to display historical information for each dynamic entity. This includes the number of previous observations to show, whether to display track lines in-between previous observations, and setting renderers.
How to use the sample
Use the controls to connect to or disconnect from the stream service, modify display properties in the dynamic entity layer, and purge all observations from the application.
How it works
- Create an
ArcGISStreamServicewith a URL - Create and configure an
ArcGISStreamServiceFilterthen set it to the stream service to limit the amount of data coming from the server. - Configure the
DynamicEntityDataSourcePurgeOptionsto manage when entities are removed from the application’s cache - Add a
Rendererto the layer to customize the appearance of the latest dynamic entity observations - Update the values in the layer’s
TrackDisplayPropertiesto customize the appearance of previous observations
Relevant API
- ArcGISStreamService
- ArcGISStreamServiceFilter
- ConnectionStatus
- DynamicEntity
- DynamicEntityLayer
- DynamicEntityPurgeOptions
- TrackDisplayProperties
About the data
This sample uses a stream service that simulates live data coming from snowplows near Sandy, Utah. There are multiple vehicle types and multiple agencies operating the snowplows.
Additional information
More information about dynamic entities can be found in the [guide documentation](link goes here).
Tags
data, dynamic, entity, live, purge, real-time, service, stream, track
Sample Code
// [WriteFile Name=AddDynamicEntityLayer, Category=Layers]// [Legal]// Copyright 2023 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 "AddDynamicEntityLayer.h"
// ArcGIS Maps SDK headers#include "ArcGISStreamService.h"#include "ArcGISStreamServiceFilter.h"#include "CalloutData.h"#include "DynamicEntity.h"#include "DynamicEntityChangedInfo.h"#include "DynamicEntityDataSourcePurgeOptions.h"#include "DynamicEntityLayer.h"#include "DynamicEntityObservation.h"#include "Envelope.h"#include "Graphic.h"#include "GraphicListModel.h"#include "GraphicsOverlay.h"#include "GraphicsOverlayListModel.h"#include "IdentifyLayerResult.h"#include "LayerListModel.h"#include "Map.h"#include "MapQuickView.h"#include "MapTypes.h"#include "Point.h"#include "RealTimeTypes.h"#include "SimpleLineSymbol.h"#include "SimpleMarkerSymbol.h"#include "SimpleRenderer.h"#include "SpatialReference.h"#include "SymbolTypes.h"#include "TrackDisplayProperties.h"#include "UniqueValue.h"#include "UniqueValueRenderer.h"#include "Viewpoint.h"
// Qt headers#include <QFuture>
using namespace Esri::ArcGISRuntime;
namespace{// This envelope is a limited region around Sandy, Utah. It will be the extent used by the `DynamicEntityFilter`.const Envelope utahSandyEnvelope( Point(-112.110052, 40.718083, SpatialReference::wgs84()), Point(-111.814782, 40.535247, SpatialReference::wgs84()));}
AddDynamicEntityLayer::AddDynamicEntityLayer(QObject* parent /* = nullptr */): QObject(parent), m_map(new Map(BasemapStyle::ArcGISDarkGray, this)){ // Create a dynamic entity data source from a given URL const QUrl streamServiceUrl("https://realtimegis2016.esri.com:6443/arcgis/rest/services/SandyVehicles/StreamServer"); m_dynamicEntityDataSource = new ArcGISStreamService(streamServiceUrl, this);
// Create and set an ArcGISStreamServiceFilter to filter what data is received from the server ArcGISStreamServiceFilter* streamServiceFilter = new ArcGISStreamServiceFilter(this); streamServiceFilter->setGeometry(utahSandyEnvelope); streamServiceFilter->setWhereClause("speed > 0"); m_dynamicEntityDataSource->setFilter(streamServiceFilter);
// Set purge options to manage when entities are removed from the cache m_dynamicEntityDataSource->purgeOptions()->setMaximumDuration(300.0 /*seconds*/);
// Handle signals emitted when connection status changes to update the UI connect(m_dynamicEntityDataSource, &ArcGISStreamService::connectionStatusChanged, this, &AddDynamicEntityLayer::connectionStatusChanged);
// Create a dynamic entity layer to display on the map and set the properties m_dynamicEntityLayer = new DynamicEntityLayer(m_dynamicEntityDataSource, this);
// Set the track display properties to change what is displayed to the user m_dynamicEntityLayer->trackDisplayProperties()->setShowTrackLine(true); m_dynamicEntityLayer->trackDisplayProperties()->setShowPreviousObservations(true);
// Create renderers for observations and their tracklines to change how they are styled
// Create a unique value renderer for the latest observations QList<UniqueValue*> entityValues; entityValues.append(new UniqueValue("","", {3}, new SimpleMarkerSymbol(SimpleMarkerSymbolStyle::Circle, Qt::magenta, 8, this), this)); entityValues.append(new UniqueValue("","", {4}, new SimpleMarkerSymbol(SimpleMarkerSymbolStyle::Circle, Qt::green, 8, this), this));
UniqueValueRenderer* entityRenderer = new UniqueValueRenderer("", new SimpleMarkerSymbol(SimpleMarkerSymbolStyle::Circle, Qt::blue, 8, this), {"agency"}, entityValues, this); m_dynamicEntityLayer->setRenderer(entityRenderer);
// Create a unique value renderer for the previous observations QList<UniqueValue*> previousObservationValues;
previousObservationValues.append(new UniqueValue("","", {3}, new SimpleMarkerSymbol(SimpleMarkerSymbolStyle::Circle, Qt::magenta, 3, this), this)); previousObservationValues.append(new UniqueValue("","", {4}, new SimpleMarkerSymbol(SimpleMarkerSymbolStyle::Circle, Qt::green, 3, this), this));
UniqueValueRenderer* trackRenderer = new UniqueValueRenderer("", new SimpleMarkerSymbol(SimpleMarkerSymbolStyle::Circle, Qt::blue, 3, this), {"agency"}, previousObservationValues); m_dynamicEntityLayer->trackDisplayProperties()->setPreviousObservationRenderer(trackRenderer);
// Use a simple renderer to change the style of the trackline m_dynamicEntityLayer->trackDisplayProperties()->setTrackLineRenderer(new SimpleRenderer(new SimpleLineSymbol(SimpleLineSymbolStyle::Solid, Qt::lightGray, 2, this)));
m_map->operationalLayers()->append(m_dynamicEntityLayer);}
AddDynamicEntityLayer::~AddDynamicEntityLayer() = default;
void AddDynamicEntityLayer::init(){ // Register the map view for QML qmlRegisterType<MapQuickView>("Esri.Samples", 1, 0, "MapView"); qmlRegisterType<AddDynamicEntityLayer>("Esri.Samples", 1, 0, "AddDynamicEntityLayerSample");}
MapQuickView* AddDynamicEntityLayer::mapView() const{ return m_mapView;}
// Set the view (created in QML)void AddDynamicEntityLayer::setMapView(MapQuickView* mapView){ if (!mapView || mapView == m_mapView) return;
m_mapView = mapView; m_mapView->setMap(m_map);
// Create and show a dashed line around the filter area GraphicsOverlay* borderOverlay = new GraphicsOverlay(this); borderOverlay->graphics()->append(new Graphic(utahSandyEnvelope, new SimpleLineSymbol(SimpleLineSymbolStyle::Dash, Qt::red, 2, this), this)); m_mapView->graphicsOverlays()->append(borderOverlay);
// Set the initial viewpoint to this area m_mapView->setViewpointAndWait(Viewpoint(utahSandyEnvelope));
// Create a slot to listen for mouse clicks connect(m_mapView, &MapQuickView::mouseClicked, this, &AddDynamicEntityLayer::identifyLayerAtMouseClick);
emit mapViewChanged();}
void AddDynamicEntityLayer::setObservationsPerTrack(int observationsPerTrack){ // Update the number of entity observations displayed using the value from the UI slider m_dynamicEntityLayer->trackDisplayProperties()->setMaximumObservations(observationsPerTrack);}
void AddDynamicEntityLayer::showTrackLines(bool showTrackLines){ // Show or hide the lines that connect previous observations m_dynamicEntityLayer->trackDisplayProperties()->setShowTrackLine(showTrackLines);}
void AddDynamicEntityLayer::showPreviousObservations(bool showPreviousObservations){ // Show or hide previous observations (if maximum observations is greater than 1) m_dynamicEntityLayer->trackDisplayProperties()->setShowPreviousObservations(showPreviousObservations);}
QString AddDynamicEntityLayer::connectionStatus() const{ // Return the current dynamic entity data source connection status as a string to display in the UI switch (m_dynamicEntityDataSource->connectionStatus()) { case ConnectionStatus::Disconnected: return "Disconnected"; case ConnectionStatus::Connecting: return "Connecting"; case ConnectionStatus::Connected: return "Connected"; case ConnectionStatus::Failed: return "Failed"; default: return "Unknown"; }}
void AddDynamicEntityLayer::enableDisableConnection(){ // Handle the UI connection switch and disable or enable connection switch (m_dynamicEntityDataSource->connectionStatus()) { case ConnectionStatus::Disconnected: { auto future = m_dynamicEntityDataSource->connectDataSourceAsync(); Q_UNUSED(future) break; } case ConnectionStatus::Connecting: // Do nothing and allow data source to finish connecting break; case ConnectionStatus::Connected: { auto future = m_dynamicEntityDataSource->disconnectDataSourceAsync(); Q_UNUSED(future) break; } case ConnectionStatus::Failed: qWarning() << "Unable to connect to dynamic entity data source"; break; default: break; }}
void AddDynamicEntityLayer::purgeAllObservations(){ // Remove all current observations from the cache auto future = m_dynamicEntityDataSource->purgeAllAsync(); Q_UNUSED(future)}
void AddDynamicEntityLayer::identifyLayerAtMouseClick(const QMouseEvent& e){ // Hide the callout (if it is already hidden this will do nothing) m_mapView->calloutData()->setVisible(false);
m_mapView->identifyLayerAsync(m_dynamicEntityLayer, e.position(), 5, false, this) .then(this, [this](IdentifyLayerResult* result) { if (!result || result->geoElements().empty()) { return; }
if (DynamicEntityObservation* observation = dynamic_cast<DynamicEntityObservation*>(result->geoElements().constFirst()); observation) { DynamicEntity* dynamicEntity = observation->dynamicEntity(); if (!dynamicEntity) { return; } m_mapView->calloutData()->setGeoElement(dynamicEntity); // Create a arcade expression for title to display the dynamic entity's attributes in the callout. const QString titleExpression = "concatenate($feature.vehiclename, \": \", $feature.speed, \" mph\")"; m_mapView->calloutData()->setTitleExpression(titleExpression);
// Create a arcade expression for detail to display the dynamic entity's attributes in the callout. const QString detailExpression = "concatenate(Round($feature.point_x,6), \",\", Round($feature.point_y,6),\" Heading: \",$feature.heading,\"°\")"; m_mapView->calloutData()->setDetailExpression(detailExpression);
// Show the callout when the title is available. connect(m_mapView->calloutData(), &CalloutData::titleChanged, this, [this]() { m_mapView->calloutData()->setVisible(true); }, Qt::SingleShotConnection); } });}// [WriteFile Name=AddDynamicEntityLayer, Category=Layers]// [Legal]// Copyright 2023 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 ADDDYNAMICENTITYLAYER_H#define ADDDYNAMICENTITYLAYER_H
// Qt headers#include <QObject>
namespace Esri::ArcGISRuntime{class ArcGISStreamService;class DynamicEntityLayer;class Map;class MapQuickView;}
class QMouseEvent;
Q_MOC_INCLUDE("MapQuickView.h");
class AddDynamicEntityLayer : public QObject{ Q_OBJECT
Q_PROPERTY(Esri::ArcGISRuntime::MapQuickView* mapView READ mapView WRITE setMapView NOTIFY mapViewChanged) Q_PROPERTY(QString connectionStatus READ connectionStatus NOTIFY connectionStatusChanged)
public: explicit AddDynamicEntityLayer(QObject* parent = nullptr); ~AddDynamicEntityLayer() override;
static void init();
Q_INVOKABLE void purgeAllObservations(); Q_INVOKABLE void setObservationsPerTrack(int observationsPerTrack); Q_INVOKABLE void showTrackLines(bool showTrackLines); Q_INVOKABLE void showPreviousObservations(bool showPreviousObservations); Q_INVOKABLE void enableDisableConnection();
signals: void mapViewChanged(); void connectionStatusChanged();
private: Esri::ArcGISRuntime::MapQuickView* mapView() const; void setMapView(Esri::ArcGISRuntime::MapQuickView* mapView);
QString connectionStatus() const;
void identifyLayerAtMouseClick(const QMouseEvent& e);
Esri::ArcGISRuntime::Map* m_map = nullptr; Esri::ArcGISRuntime::MapQuickView* m_mapView = nullptr;
Esri::ArcGISRuntime::ArcGISStreamService* m_dynamicEntityDataSource = nullptr; Esri::ArcGISRuntime::DynamicEntityLayer* m_dynamicEntityLayer = nullptr;};
#endif // ADDDYNAMICENTITYLAYER_H// [WriteFile Name=AddDynamicEntityLayer, Category=Layers]// [Legal]// Copyright 2023 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 Esri.Samplesimport Esri.ArcGISRuntime.Toolkit
Item { // add a mapView component MapView { id: view anchors.fill: parent
Component.onCompleted: { // Set and keep the focus on MapView to enable keyboard navigation forceActiveFocus(); } }
// Declare the C++ instance which creates the map etc. and supply the view AddDynamicEntityLayerSample { id: model mapView: view onConnectionStatusChanged: { // Enable switch if data stream is successfully disconnected or connected statusSwitch.enabled = (["Disconnected", "Connected"].indexOf(model.connectionStatus) !== -1) } }
Callout { id: callout height: 60 calloutData: view.calloutData accessoryButtonVisible: false }
Rectangle { id: dynamicEntityLayerOptions anchors { top: parent.top right: parent.right margins: 10 } width: (300 < parent.width - 20) ? 300 : parent.width - 20 height: column.height + 20 border.width: 1
// Catch mouse signals so they don't propagate to the map MouseArea { anchors.fill: parent onClicked: mouse => mouse.accepted = true onWheel: wheel => wheel.accepted = true }
Column { id: column anchors { top: parent.top left: parent.left right: parent.right margins: 10 }
Text { id: statusText anchors.horizontalCenter: parent.horizontalCenter text: "Status: " + model.connectionStatus font.pixelSize: 18 horizontalAlignment: Text.AlignHCenter font.bold: true }
Switch { id: statusSwitch anchors.horizontalCenter: parent.horizontalCenter checked: model.connectionStatus !== "Disconnected" onCheckedChanged: { model.enableDisableConnection(); // Calls either of the following depending on the state // m_dynamicEntityDataSource->connectDataSource(); // m_dynamicEntityDataSource->disconnectDataSource(); } }
CheckBox { id: trackLinesBox text: "Track lines" checked: true onCheckedChanged: { model.showTrackLines(checked); // Calls m_dynamicEntityLayer->trackDisplayProperties()->setShowTrackLine(showTrackLines); } }
CheckBox { id: previousObservationsBox text: "Previous observations" checked: true onCheckedChanged: { model.showPreviousObservations(checked); // Calls m_dynamicEntityLayer->trackDisplayProperties()->setShowPreviousObservations(showPreviousObservations); } }
Text { id: observationsSliderText topPadding: 10 text: "Observations per track (" + observationsSlider.value + ")" }
Slider { id: observationsSlider anchors { left: parent.left right: parent.right } value: 5 stepSize: 1 from: 1 to: 16 onValueChanged: { model.setObservationsPerTrack(value) // Calls m_dynamicEntityLayer->trackDisplayProperties()->setMaximumObservations(observationsPerTrack); } }
Button { id: purgeButton anchors.horizontalCenter: parent.horizontalCenter text: "Purge all observations" onClicked: { callout.visible = false; model.purgeAllObservations(); // Calls m_dynamicEntityDataSource->purgeAll(); } } } }}// [Legal]// Copyright 2023 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 "AddDynamicEntityLayer.h"
// ArcGIS Maps SDK headers#include "ArcGISRuntimeEnvironment.h"
// Qt headers#include <QCommandLineParser>#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("AddDynamicEntityLayer"));
// 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 AddDynamicEntityLayer::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/Layers/AddDynamicEntityLayer/main.qml"));
return app.exec();}// Copyright 2023 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
AddDynamicEntityLayer { anchors.fill: parent }}