Create a custom dynamic entity data source and display it using a dynamic entity layer.

Use case
Developers can create a custom DynamicEntityDataSource to be able to visualize data from a variety of different feeds as dynamic entities using a DynamicEntityLayer. An example of this is in a mobile situational awareness app, where a custom DynamicEntityDataSource can be used to connect to peer-to-peer feeds in order to visualize real-time location tracks from teammates in the field.
How to use the sample
Run the sample to view the map and the dynamic entity layer displaying the latest observation from the custom data source. Tap on a dynamic entity to view its attributes in a callout.
How it works
Configure the custom data source:
- Create a custom data source implementation of a
DynamicEntityDataSource. - Override
OnLoadAsync()to specify theDynamicEntityDataSourceInfofor a given unique entity ID field and a list ofFieldobjects matching the fields in the data source. - Override
OnConnectAsync()to begin processing observations from the custom data source. - Loop through the observations and deserialize each observation into a
Pointobject and aQVariantMapcontaining the attributes. - Use
DynamicEntityDataSource::addObservation(mapPoint, attributes)to add each observation to the custom data source.
Configure the map view:
- Create a
DynamicEntityLayerusing the custom data source implementation. - Update values in the layer’s
TrackDisplayPropertiesto customize the layer’s appearance. - Set up the layer’s
LabelDefinitionsto display labels for each dynamic entity. - Use
MapView::identifyLayerAsyncto select a dynamic entity and display the entity’s attributes in aCallout.
Relevant API
- DynamicEntity
- DynamicEntityDataSource
- DynamicEntityLayer
- LabelDefinition
- TrackDisplayProperties
About the data
This sample uses a .json file containing observations of marine vessels in the Pacific North West hosted on ArcGIS Online .
Additional information
In this sample, we iterate through features in a GeoJSON file to mimic messages coming from a real-time feed. You can create a custom dyamic entity data source to process any data that contains observations which can be translated into Point objects with associated QVariantMap attributes.
Tags
data, dynamic, entity, label, labeling, live, real-time, stream, track
Sample Code
// [WriteFile Name=AddCustomDynamicEntityDataSource, 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 "AddCustomDynamicEntityDataSource.h"#include "CustomDataSource.h"
// ArcGIS Maps SDK headers#include "ArcGISMapImageLayer.h"#include "AttributeListModel.h"#include "Basemap.h"#include "CalloutData.h"#include "DynamicEntity.h"#include "DynamicEntityChangedInfo.h"#include "DynamicEntityDataSource.h"#include "DynamicEntityDataSourcePurgeOptions.h"#include "DynamicEntityLayer.h"#include "DynamicEntityObservation.h"#include "IdentifyLayerResult.h"#include "LabelDefinition.h"#include "LabelDefinitionListModel.h"#include "LayerListModel.h"#include "Map.h"#include "MapQuickView.h"#include "MapTypes.h"#include "ServiceTypes.h"#include "SimpleLabelExpression.h"#include "TextSymbol.h"#include "TrackDisplayProperties.h"#include "Viewpoint.h"
// Qt headers#include <QFuture>#include <QtConcurrent/QtConcurrent>
using namespace Esri::ArcGISRuntime;
AddCustomDynamicEntityDataSource::AddCustomDynamicEntityDataSource(QObject* parent /* = nullptr */): QObject(parent), m_map(new Map(BasemapStyle::ArcGISOceans, this)){ // This is a custom class that inherits from DynamicEntityDataSource. It was written specifically for this sample. CustomDataSource* dataSource = new CustomDataSource(":/Samples/Layers/AddCustomDynamicEntityDataSource/AIS_MarineCadastre_SelectedVessels_CustomDataSource.json", "MMSI", 10, this); m_dynamicEntityLayer = new DynamicEntityLayer(dataSource, this);
m_map->operationalLayers()->append(m_dynamicEntityLayer);
// Set previous observation properties m_dynamicEntityLayer->trackDisplayProperties()->setShowPreviousObservations(true); m_dynamicEntityLayer->trackDisplayProperties()->setShowTrackLine(true); m_dynamicEntityLayer->trackDisplayProperties()->setMaximumObservations(20);
// Even when not displayed, previous observations are stored until purged m_dynamicEntityLayer->dataSource()->purgeOptions()->setMaximumObservationsPerTrack(20);
// Show the vessel names as labels above the observation points SimpleLabelExpression* simpleLabelExpression = new SimpleLabelExpression("[VesselName]", this); TextSymbol* labelSymbol = new TextSymbol(this); labelSymbol->setColor(Qt::red); labelSymbol->setSize(12); LabelDefinition* labelDef = new LabelDefinition(simpleLabelExpression, labelSymbol, this); labelDef->setPlacement(LabelingPlacement::PointAboveCenter); m_dynamicEntityLayer->labelDefinitions()->append(labelDef); m_dynamicEntityLayer->setLabelsEnabled(true);}
AddCustomDynamicEntityDataSource::~AddCustomDynamicEntityDataSource() = default;
void AddCustomDynamicEntityDataSource::init(){ // Register the map view for QML qmlRegisterType<MapQuickView>("Esri.Samples", 1, 0, "MapView"); qmlRegisterType<AddCustomDynamicEntityDataSource>("Esri.Samples", 1, 0, "AddCustomDynamicEntityDataSourceSample");}
MapQuickView* AddCustomDynamicEntityDataSource::mapView() const{ return m_mapView;}
// Set the view (created in QML)void AddCustomDynamicEntityDataSource::setMapView(MapQuickView* mapView){ if (!mapView || mapView == m_mapView) return;
m_mapView = mapView; m_mapView->setMap(m_map);
m_mapView->setViewpointAsync(Viewpoint(47.984, -123.657, 3e6));
// Create a slot to listen for mouse clicks connect(m_mapView, &MapQuickView::mouseClicked, this, &AddCustomDynamicEntityDataSource::identifyLayerAtMouseClick);
emit mapViewChanged();}
void AddCustomDynamicEntityDataSource::identifyLayerAtMouseClick(const QMouseEvent &e){ // Hide the callout (if it is already hidden this will do nothing) m_mapView->calloutData()->setVisible(false);
// Reseting m_tempParent gives it a new parent and cleans up any previously owned children like IdentifyLayerResult and DynamicEntity objects m_tempParent.reset(new QObject(this));
m_mapView->identifyLayerAsync(m_map->operationalLayers()->first(), e.position(), 10, false, m_tempParent.get()) .then(this, [this](IdentifyLayerResult* result) { if (!result || result->geoElements().empty()) return;
if (DynamicEntityObservation* observation = dynamic_cast<DynamicEntityObservation*>(result->geoElements().constFirst())) { DynamicEntity* dynamicEntity = observation->dynamicEntity();
if (!dynamicEntity) return;
// Get updated info about the dynamic entity every time it updates connect(dynamicEntity, &DynamicEntity::dynamicEntityChanged, this, [this](DynamicEntityChangedInfo* changedInfo) { // changedInfo will be cleaned up when m_tempParent is reset, but they will persist until then // a new DynamicEntityChangedInfo object will be created every time the dynamic entity updates // we can call deleteLater() to delete the object sooner when we leave this event loop changedInfo->deleteLater();
// Get the current/most recent observation and populate a popup with its information DynamicEntityObservation* currentObservation = changedInfo->receivedObservation(); QString calloutText = { "Vessel Name: " + currentObservation->attributes()->attributeValue("VesselName").toString() + "\n" + "Call Sign: " + currentObservation->attributes()->attributeValue("CallSign").toString() + "\n" + "Course over Ground: " + currentObservation->attributes()->attributeValue("COG").toString() + "º\n" + "Speed over Ground: " + currentObservation->attributes()->attributeValue("SOG").toString() + " knots" }; m_mapView->calloutData()->setDetail(calloutText); m_mapView->calloutData()->setGeoElement(currentObservation); m_mapView->calloutData()->setVisible(true); }); } });}// [WriteFile Name=AddCustomDynamicEntityDataSource, 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 ADDCUSTOMDYNAMICENTITYDATASOURCE_H#define ADDCUSTOMDYNAMICENTITYDATASOURCE_H
// Qt headers#include <QMouseEvent>#include <QObject>
namespace Esri::ArcGISRuntime{class DynamicEntity;class DynamicEntityLayer;class Map;class MapQuickView;}
Q_MOC_INCLUDE("MapQuickView.h");
class AddCustomDynamicEntityDataSource : public QObject{ Q_OBJECT
Q_PROPERTY(Esri::ArcGISRuntime::MapQuickView* mapView READ mapView WRITE setMapView NOTIFY mapViewChanged)
public: explicit AddCustomDynamicEntityDataSource(QObject* parent = nullptr); ~AddCustomDynamicEntityDataSource() override;
static void init();
signals: void mapViewChanged();
private: Esri::ArcGISRuntime::MapQuickView* mapView() const; void setMapView(Esri::ArcGISRuntime::MapQuickView* mapView);
void identifyLayerAtMouseClick(const QMouseEvent& e);
Esri::ArcGISRuntime::Map* m_map = nullptr; Esri::ArcGISRuntime::MapQuickView* m_mapView = nullptr;
Esri::ArcGISRuntime::DynamicEntityLayer* m_dynamicEntityLayer = nullptr; QScopedPointer<QObject> m_tempParent;};
#endif // ADDCUSTOMDYNAMICENTITYDATASOURCE_H// [WriteFile Name=AddCustomDynamicEntityDataSource, 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 AddCustomDynamicEntityDataSourceSample { id: model mapView: view }
Callout { id: callout height: 120 calloutData: view.calloutData accessoryButtonVisible: false }}// [Legal]// Copyright 2024 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 "CustomDataSource.h"
// ArcGIS Maps SDK headers#include "Domain.h"#include "DynamicEntityDataSource.h"#include "DynamicEntityDataSourceInfo.h"#include "Field.h"#include "Point.h"#include "ServiceTypes.h"#include "SpatialReference.h"
// Qt headers#include <QFile>#include <QFuture>#include <QTextStream>#include <QtConcurrent/QtConcurrent>
using namespace Esri::ArcGISRuntime;
CustomDataSource::CustomDataSource(QObject* parent) : DynamicEntityDataSource(parent){}
CustomDataSource::CustomDataSource(const QString& fileName, const QString& entityIdField, const int msDelay, QObject* parent) : DynamicEntityDataSource(parent), m_fileName(fileName), m_entityIdField(entityIdField), m_msDelay(msDelay){}
CustomDataSource::~CustomDataSource(){ // The app will crash upon destruction if the asynchronous method is still running upon destruction m_watcher.cancel(); m_watcher.waitForFinished();}
// Override the virtual onLoadAsync method to define what the DynamicEntityDataSource will do upon loadQFuture<DynamicEntityDataSourceInfo*> CustomDataSource::onLoadAsync(){ m_fields = getSchema();
m_file.setFileName(m_fileName);
if (m_file.open(QIODevice::ReadOnly | QIODevice::Text)) m_textStream.setDevice(&m_file);
// Create a DynamicEntityDataSourceInfo object to return DynamicEntityDataSourceInfo* dynamicEntityDataSourceInfo = new DynamicEntityDataSourceInfo(m_entityIdField, m_fields, this);
// Your data may not display correctly if you do not have a spatial reference set dynamicEntityDataSourceInfo->setSpatialReference(SpatialReference::wgs84());
// Return the QFuture<DynamicEntityDataSourceInfo*> return QtFuture::makeReadyValueFuture(dynamicEntityDataSourceInfo);}
// Override the virtual onConnectAsync method to define what the DynamicEntityDataSource will do when the data source is connectedQFuture<void> CustomDataSource::onConnectAsync(){ m_watcher.setFuture(QtConcurrent::run([this](){observationProcessLoopAsync();})); return QtFuture::makeReadyVoidFuture();}
// Override the virtual onDisconnectAsync method to define what the DynamicEntityDataSource will do when the data source is disconnectedQFuture<void> CustomDataSource::onDisconnectAsync(){ m_watcher.cancel(); m_watcher.waitForFinished(); return QtFuture::makeReadyVoidFuture();}
// This method runs asynchronously to step through the accompanying .json file and call addObservation(geometry, attributes) with each linevoid CustomDataSource::observationProcessLoopAsync(){ while (!m_textStream.atEnd() && !m_watcher.isCanceled()) { const QString line = m_textStream.readLine(); const QJsonObject jsonObject = QJsonDocument::fromJson(line.toUtf8()).object();
// Get the observation geometry from the line const QJsonObject geometryObject = jsonObject.value("geometry").toObject(); const Point point(geometryObject.value("x").toDouble(), geometryObject.value("y").toDouble(), SpatialReference::wgs84());
// Get the observation attributes from the line const QVariantMap attributes = jsonObject.value("attributes").toObject().toVariantMap();
addObservation(point, attributes);
QThread::msleep(m_msDelay);
if (m_textStream.atEnd()) m_textStream.seek(0); }}
// Schema fields that are hardcoded to match the accompanying .json dataQList<Field> CustomDataSource::getSchema(){ return QList<Field> { Field(FieldType::Text, "MMSI", "", 256, Domain(), false, false), Field(FieldType::Float64, "BaseDateTime", "", 8, Domain(), false, false), Field(FieldType::Float64, "LAT", "", 8, Domain(), false, false), Field(FieldType::Float64, "LONG", "", 8, Domain(), false, false), Field(FieldType::Float64, "SOG", "", 8, Domain(), false, false), Field(FieldType::Float64, "COG", "", 8, Domain(), false, false), Field(FieldType::Float64, "Heading", "", 8, Domain(), false, false), Field(FieldType::Text, "VesselName", "", 256, Domain(), false, false), Field(FieldType::Text, "IMO", "", 256, Domain(), false, false), Field(FieldType::Text, "CallSign", "", 256, Domain(), false, false), Field(FieldType::Text, "VesselType", "", 256, Domain(), false, false), Field(FieldType::Text, "Status", "", 256, Domain(), false, false), Field(FieldType::Float64, "Length", "", 8, Domain(), false, false), Field(FieldType::Float64, "Width", "", 8, Domain(), false, false), Field(FieldType::Text, "Cargo", "", 256, Domain(), false, false), Field(FieldType::Text, "globalid", "", 256, Domain(), false, false) };}// [Legal]// Copyright 2024 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 CUSTOMDATASOURCE_H#define CUSTOMDATASOURCE_H
// ArcGIS Maps SDK headers#include "DynamicEntityDataSource.h"#include "Field.h"
// Qt headers#include <QFile>#include <QFuture>#include <QFutureWatcher>#include <QJsonObject>#include <QObject>#include <QString>#include <QTextStream>#include <QUrl>#include <QVariantMap>
namespace Esri::ArcGISRuntime {
class DynamicEntityDataSource;class DynamicEntityDataSourceInfo;
class CustomDataSource : public DynamicEntityDataSource{ Q_OBJECT
public: CustomDataSource(QObject* parent = nullptr); CustomDataSource(const QString& fileName, const QString& entityIdField, const int msDelay, QObject* parent = nullptr); ~CustomDataSource() override;
QFuture<DynamicEntityDataSourceInfo*> onLoadAsync() override; QFuture<void> onConnectAsync() override; QFuture<void> onDisconnectAsync() override;
private: void observationProcessLoopAsync(); QList<Field> getSchema();
QString m_fileName; QFile m_file; QTextStream m_textStream; QString m_entityIdField; int m_msDelay; QList<Field> m_fields; QFutureWatcher<void> m_watcher;};
} // namespace Esri::ArcGISRuntime
#endif // CUSTOMDATASOURCE_H// [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 "AddCustomDynamicEntityDataSource.h"
// ArcGIS Maps SDK headers#include "ArcGISRuntimeEnvironment.h"
// Qt headers#include <QCommandLineParser>#include <QDir>#include <QGuiApplication>#include <QQmlApplicationEngine>
// Other headers#include "Esri/ArcGISRuntime/Toolkit/register.h"
// 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("AddCustomDynamicEntityDataSource"));
// 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 AddCustomDynamicEntityDataSource::init();
// Initialize application view QQmlApplicationEngine engine; Esri::ArcGISRuntime::Toolkit::registerComponents(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/AddCustomDynamicEntityDataSource/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
AddCustomDynamicEntityDataSource { anchors.fill: parent }}