Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New Sample: Add custom dynamic entity data source #1269

Merged
merged 21 commits into from
Jul 27, 2023
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage x:Class="ArcGIS.Samples.AddCustomDynamicEntityDataSource.AddCustomDynamicEntityDataSource"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:esriUI="clr-namespace:Esri.ArcGISRuntime.Maui;assembly=Esri.ArcGISRuntime.Maui">
<Grid>
<esriUI:MapView x:Name="MyMapView" GeoViewTapped="GeoViewTapped" />
</Grid>
</ContentPage>
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
// 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.

using Esri.ArcGISRuntime.ArcGISServices;
using Esri.ArcGISRuntime.Data;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Mapping.Labeling;
using Esri.ArcGISRuntime.RealTime;
using Esri.ArcGISRuntime.Symbology;
using Esri.ArcGISRuntime.UI;

namespace ArcGIS.Samples.AddCustomDynamicEntityDataSource
{
[ArcGIS.Samples.Shared.Attributes.Sample(
name: "Add custom dynamic entity data source",
category: "Layers",
description: "Display data from a custom dynamic entity data source using a dynamic entity layer.",
instructions: "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.",
tags: new[] { "data", "dynamic", "entity", "label", "labeling", "live", "real-time", "stream", "track" })]
[ArcGIS.Samples.Shared.Attributes.ClassFile("SimulatedDataSource.cs")]
public partial class AddCustomDynamicEntityDataSource
{
public AddCustomDynamicEntityDataSource()
{
InitializeComponent();
Initialize();
}

private void Initialize()
{
// Create a new map with the navigation basemap style.
MyMapView.Map = new Map(BasemapStyle.ArcGISNavigation);

// Set the initial viewpoint.
MyMapView.SetViewpoint(new Viewpoint(47.984036751327544, -123.65671327050406, 3000000));

// Create a new custom file source.
// This takes the path to the simulation file, field name that will be used as the entity id, and the delay between each observation that is processed.
// In this example we are using a json file as our custom data source.
// This field value should be a unique identifier for each entity.
// Adjusting the value for the delay will change the speed at which the entities and their observations are displayed.
var customSource = new SimulatedDataSource("AIS_MarineCadastre_SelectedVessels_CustomDataSource.json", "MMSI", TimeSpan.FromMilliseconds(10));

// Create the dynamic entity layer using the custom data source.
var dynamicEntityLayer = new DynamicEntityLayer(customSource);

// Set up the track display properties.
SetupTrackDisplayProperties(dynamicEntityLayer);

// Set up the dynamic entity labeling.
SetupLabeling(dynamicEntityLayer);

// Add the dynamic entity layer to the map.
MyMapView.Map.OperationalLayers.Add(dynamicEntityLayer);
}

private void SetupTrackDisplayProperties(DynamicEntityLayer layer)
{
// Set up the track display properties, these properties will be used to configure the appearance of the track line and previous observations.
layer.TrackDisplayProperties.ShowPreviousObservations = true;
layer.TrackDisplayProperties.ShowTrackLine = true;
layer.TrackDisplayProperties.MaximumObservations = 20;
}

private void SetupLabeling(DynamicEntityLayer layer)
{
// Define the label expression to be used, in this case we will use the "VesselName" for each of the dynamic entities.
var simpleLabelExpression = new SimpleLabelExpression("[VesselName]");

// Set the text symbol color and size for the labels.
var labelSymbol = new TextSymbol() { Color = System.Drawing.Color.Red, Size = 12d };

// Set the label position.
var labelDef = new LabelDefinition(simpleLabelExpression, labelSymbol) { Placement = LabelingPlacement.PointAboveCenter };

// Add the label definition to the dynamic entity layer and enable labels.
layer.LabelDefinitions.Add(labelDef);
layer.LabelsEnabled = true;
}

private async void GeoViewTapped(object sender, Esri.ArcGISRuntime.Maui.GeoViewInputEventArgs e)
{
e.Handled = true;
try
{
MyMapView.DismissCallout();

// If no dynamic entity layer is present in the map, return.
var layer = MyMapView.Map?.OperationalLayers.OfType<DynamicEntityLayer>().FirstOrDefault();
if (layer is null) return;

// Identify the tapped observation.
IdentifyLayerResult results = await MyMapView.IdentifyLayerAsync(layer, e.Position, 2d, false);
DynamicEntityObservation observation = results.GeoElements.FirstOrDefault() as DynamicEntityObservation;
if (observation is null) return;

// Get the dynamic entity from the observation.
var dynamicEntity = observation.GetDynamicEntity();
if (dynamicEntity is null) return;

// The standard callout takes care of moving when the dynamic entity changes.
var calloutDef = new CalloutDefinition(dynamicEntity);
if (layer.Renderer?.GetSymbol(dynamicEntity) is Symbol symbol)
{
await calloutDef.SetIconFromSymbolAsync(symbol);
}

// Show the callout for the tapped dynamic entity.
MyMapView.ShowCalloutForGeoElement(dynamicEntity, e.Position, calloutDef);
}
catch (Exception ex)
{
await DisplayAlert("Error identifying dynamic entity.", ex.ToString(), "Ok");
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,195 @@
// 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.

using Esri.ArcGISRuntime.Data;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.RealTime;
using System.Diagnostics;
using System.Text.Json;


namespace ArcGIS.Samples.AddCustomDynamicEntityDataSource
{
public class SimulatedDataSource : DynamicEntityDataSource
{
// Hold a reference to the file stream reader, the process task, and the cancellation token source.
private Task? _processTask;
private StreamReader? _streamReader;
private CancellationTokenSource? _cancellationTokenSource;
private List<Field> _fields;

public SimulatedDataSource(string fileName, string entityIdField, TimeSpan delay)
{
FileName = fileName;
EntityIdField = entityIdField;
Delay = delay;
}

#region Properties

// Expose the file path, entity ID field, and delay length as properties.
public string FileName { get; }
public string EntityIdField { get; }
public TimeSpan Delay { get; }

#endregion

protected override async Task<DynamicEntityDataSourceInfo> OnLoadAsync()
{
// Derive schema from the first row in the custom data source.
_fields = GetSchema();

// Open the file for processing.
Stream stream = await FileSystem.OpenAppPackageFileAsync(FileName);
_streamReader = new StreamReader(stream);

// Create a new DynamicEntityDataSourceInfo using the entity ID field and the fields derived from the attributes of each observation in the custom data source.
return new DynamicEntityDataSourceInfo(EntityIdField, _fields) { SpatialReference = SpatialReferences.Wgs84 };
}

protected override Task OnConnectAsync(CancellationToken cancellationToken)
{
// On connecting to the custom data source begin processing the file.
_cancellationTokenSource = new();
_processTask = Task.Run(() => ObservationProcessLoopAsync(), _cancellationTokenSource.Token);
return Task.CompletedTask;
}

protected override async Task OnDisconnectAsync()
{
// On disconnecting from the custom data source, stop processing the file.
_cancellationTokenSource?.Cancel();

if (_processTask is not null) await _processTask;

_cancellationTokenSource = null;
_processTask = null;
}

private async Task ObservationProcessLoopAsync()
{
try
{
while (!_cancellationTokenSource!.IsCancellationRequested)
{
// Process the next observation.
var processed = await ProcessNextObservation();

// If the end of the file has been reached, break out of the loop.
if (_streamReader.EndOfStream) break;

// If the observation was not processed, continue to the next observation.
if (!processed) continue;

// If there is no delay, yield to the UI thread otherwise delay for the specified amount of time.
if (Delay == TimeSpan.Zero)
{
await Task.Yield();
}
else
{
await Task.Delay(Delay, _cancellationTokenSource.Token);
}
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
}
}

private async Task<bool> ProcessNextObservation()
{
_ = _streamReader ?? throw new ArgumentNullException("File stream not available.");

// Read the next observation.
var json = await _streamReader.ReadLineAsync();

// If there is no json to read or the schema is not available, return false.
if (string.IsNullOrEmpty(json) || _fields is null) return false;

try
{
JsonElement jsonElement = JsonSerializer.Deserialize<JsonElement>(json);

// Create a new MapPoint from the x and y coordinates of the observation.
MapPoint? point = null;
if (jsonElement.TryGetProperty("geometry", out JsonElement jsonGeometry))
{
point = new MapPoint(
jsonGeometry.GetProperty("x").GetDouble(),
jsonGeometry.GetProperty("y").GetDouble(),
SpatialReferences.Wgs84);
}

// Get the dictionary of attributes from the observation using the field names as keys.
Dictionary<string, object?> attributes = new();
if (jsonElement.TryGetProperty("attributes", out JsonElement jsonAttributes))
{
foreach (var field in _fields)
{
if (jsonAttributes.TryGetProperty(field.Name, out JsonElement prop))
{
object? value = null;
if (prop.ValueKind != JsonValueKind.Null)
{
if (prop.ValueKind == JsonValueKind.Number && field.FieldType == FieldType.Float64)
{
value = prop.GetDouble();
}
else if (prop.ValueKind == JsonValueKind.Number && field.FieldType == FieldType.Int32)
{
value = prop.GetInt32();
}
else if (prop.ValueKind == JsonValueKind.String)
{
value = prop.GetString();
}
}
attributes.Add(field.Name, value);
}
}
}

// Add the observation to the custom data source.
AddObservation(point, attributes);
return true;
}
catch (Exception ex)
{
Debug.WriteLine($"{ex}");
return false;
}
}

private static List<Field> GetSchema()
{
// Return a list of fields matching the attributes of each observation in the custom data source.
return new List<Field>()
{
new Field(FieldType.Text, "MMSI", string.Empty, 256),
new Field(FieldType.Float64, "BaseDateTime", string.Empty, 8),
new Field(FieldType.Float64, "LAT", string.Empty, 8),
new Field(FieldType.Float64, "LONG", string.Empty, 8),
new Field(FieldType.Float64, "SOG", string.Empty, 8),
new Field(FieldType.Float64, "COG", string.Empty, 8),
new Field(FieldType.Float64, "Heading", string.Empty, 8),
new Field(FieldType.Text, "VesselName", string.Empty, 256),
new Field(FieldType.Text, "IMO", string.Empty, 256),
new Field(FieldType.Text, "CallSign", string.Empty, 256),
new Field(FieldType.Text, "VesselType", string.Empty, 256),
new Field(FieldType.Text, "Status", string.Empty, 256),
new Field(FieldType.Float64, "Length", string.Empty, 8),
new Field(FieldType.Float64, "Width", string.Empty, 8),
new Field(FieldType.Text, "Cargo", string.Empty, 256),
new Field(FieldType.Text, "globalid", string.Empty, 256)
};
}
}
}
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# Add custom dynamic entity data source

Display data from a custom dynamic entity data source using a dynamic entity layer.

![Image of add custom dynamic entity data source](addcustomdynamicentitydatasource.jpg)

## Use case

Using this API developers can connect their own feed as a custom `DynamicEntityDataSource` to leverage observations using a `DynamicEntityLayer`. An example of this is in a mobile situational awareness app where a custom `DynamicEntityDataSource` can connect to Peer to Peer feeds to visualize real time location tracks.

## 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:

1. Create a custom data source implementation of a `DynamicDataSource`.
2. Override `OnLoadAsync()` to specify the `DynamicEntityDataSourceInfo` for a given unique entity ID field and a list of `Field` objects matching the fields in the data source.
3. Override `OnConnectAsync()` to begin processing observations from the custom data source.
4. Loop through the observations and deserialize each observation into a `MapPoint` object and a `Dictionary<string, object>` containing the attributes.
5. Use `AddObservation(mapPoint, attributes)` to add each observation to the custom data source.

Configure the map view:

1. Create a `DynamicEntityLayer` using the custom data source implementation.
2. Update values in the layer's `TrackDisplayProperties` to customize the layer's appearance.
3. Set up the layer's `LabelDefinitions` to display labels for each dynamic entity.
4. Configure a `GeoViewTapped` event handler on the `MapView` to select a dynamic entity and display the entity's attributes in a callout.

## 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.

## Additional information

While this sample demonstrates the use of a .json file as a custom data source, you can use any data source that contains observations which can be translated into `MapPoint` objects with associated `Dictionary<string, object>` attributes.

## Tags

data, dynamic, entity, label, labeling, live, real-time, stream, track
Loading