Find dynamic entities from a data source that match a query.

Use case
Developers can query a DynamicEntityDataSource to find dynamic entities that meet spatial and/or attribute criteria. The query returns a collection of dynamic entities matching the DynamicEntityQueryParameters or Track IDs at the moment the query is executed. An example of this is a flight tracking app that monitors airspace near a particular airport, allowing the user to monitor flights based on different criteria such as arrival airport or flight number.
How to use the sample
Tap the “Query Flights” button and select a query to perform from the menu. Once the query is complete, a list of the resulting flights will be displayed. Tap on a flight to see its latest attributes in real-time.
How it works
- Create a
DynamicEntityDataSourceto stream dynamic entity events. - Create a
DynamicEntityLayerusing the data source and add it to the map’s operational layers. - Create
DynamicEntityQueryParametersand set its properties to specify the parameters for the query:- To spatially filter results, set the
geometryandspatialRelationship. The spatial relationship isintersectsby default. - To query entities with certain attribute values, set the
whereClause. - To get entities with specific track IDs, modify the
trackIDscollection.
- To spatially filter results, set the
- To perform a dynamic entities query, use
DynamicEntityDataSource.QueryDynamicEntitiesAsync()to query with multiple criteria (such as track IDs, spatial, and/or attribute filters), or useDynamicEntityDataSource.QueryDynamicEntitiesAsync(trackIDs)if you want to query only by track IDs. - When complete, iterate through the returned collection of
DynamicEntityobjects from the result. - Use the
DynamicEntity.DynamicEntityChangedevent to get real-time updates when entity attributes change. - Get the new observation from the resulting
DynamicEntityChangedEventArgsusing theReceivedObservationproperty to update the UI with current information.
Relevant API
- DynamicEntity
- DynamicEntityChangedInfo
- DynamicEntityDataSource
- DynamicEntityDataSourceInfo
- DynamicEntityLayer
- DynamicEntityObservation
- DynamicEntityQueryParameters
- DynamicEntityQueryResult
About the data
This sample uses the PHX Air Traffic JSON portal item, which is hosted on ArcGIS Online and downloaded automatically. The file contains JSON data for mock air traffic around the Phoenix Sky Harbor International Airport in Phoenix, AZ, USA. The decoded data is used to simulate dynamic entity events through a CustomDynamicEntityDataSource, which is displayed on the map with a DynamicEntityLayer.
Additional information
A dynamic entities query is performed on the most recent observation of each dynamic entity in the data source at the time the query is executed. As the dynamic entities change, they may no longer match the query parameters.
Tags
data, dynamic, entity, live, query, real-time, search, stream, track
Sample Code
// Copyright 2025 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.Geometry;using Esri.ArcGISRuntime.RealTime;using System.Text.Json;
namespace ArcGIS.Samples.QueryDynamicEntities{ public class CustomStreamService : DynamicEntityDataSource { private readonly DynamicEntityDataSourceInfo _info; private readonly string _dataPath; private readonly TimeSpan _delay; private CancellationTokenSource _cancellationTokenSource; private Task _dataFeedTask;
// Initializes the custom stream service with data source info and file path. public CustomStreamService(DynamicEntityDataSourceInfo info, string dataPath, TimeSpan delay) { _info = info; _dataPath = dataPath; _delay = delay; }
// Returns the data source information while loading the service. protected override Task<DynamicEntityDataSourceInfo> OnLoadAsync() => Task.FromResult(_info);
// Starts the data feed processing task when connecting to the service. protected override Task OnConnectAsync(CancellationToken cancellationToken) { _cancellationTokenSource = new CancellationTokenSource(); _dataFeedTask = ProcessDataFeedAsync(_cancellationTokenSource.Token); return Task.CompletedTask; }
// Cancels the data feed processing task and cleans up resources when disconnecting from the service. protected override async Task OnDisconnectAsync() { _cancellationTokenSource?.Cancel();
if (_dataFeedTask != null) { try { await _dataFeedTask; } catch (OperationCanceledException) { } }
_cancellationTokenSource?.Dispose(); }
// Reads and processes flight data from JSON file line by line with delays. private async Task ProcessDataFeedAsync(CancellationToken cancellationToken) { try { if (!File.Exists(_dataPath)) throw new FileNotFoundException("Flight data file not found.", _dataPath);
// Read all lines off the UI thread. Each line should contain one JSON object. var lines = await File.ReadAllLinesAsync(_dataPath, cancellationToken);
foreach (var line in lines) { if (cancellationToken.IsCancellationRequested) break;
try { // Parse a single JSON line (newline-delimited JSON format). using (JsonDocument document = JsonDocument.Parse(line)) { var root = document.RootElement;
// Geometry section (expected: { "geometry": { "x": <double>, "y": <double> } }) if (root.TryGetProperty("geometry", out JsonElement geometryElement)) { double x = 0, y = 0;
// Extract X coordinate (defaults remain 0 if missing or invalid). if (geometryElement.TryGetProperty("x", out JsonElement xElement)) x = xElement.GetDouble();
// Extract Y coordinate. if (geometryElement.TryGetProperty("y", out JsonElement yElement)) y = yElement.GetDouble();
// Create geometry in WGS84. var point = new MapPoint(x, y, SpatialReferences.Wgs84);
// Collect attribute key/value pairs. var attributes = new Dictionary<string, object>();
if (root.TryGetProperty("attributes", out JsonElement attributesElement)) { foreach (var property in attributesElement.EnumerateObject()) { object value = property.Value.ValueKind switch { JsonValueKind.String => property.Value.GetString(), JsonValueKind.Number when property.Value.TryGetInt32(out int intValue) => intValue, JsonValueKind.Number => property.Value.GetDouble(), JsonValueKind.True => true, JsonValueKind.False => false, JsonValueKind.Null => null, _ => property.Value.ToString() };
attributes[property.Name] = value; } } // Add the observation to the data source. AddObservation(point, attributes); } } // Introduce a delay to simulate real-time data feed. await Task.Delay(_delay, cancellationToken); } catch (JsonException ex) { System.Diagnostics.Debug.WriteLine($"Error parsing JSON line: {ex.Message}"); continue; } } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine($"Data feed error: {ex.Message}"); } } }}// Copyright 2025 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.RealTime;using System.Collections.Generic;using System.ComponentModel;using System.Runtime.CompilerServices;
namespace ArcGIS.Samples.QueryDynamicEntities{ public class FlightInfo : INotifyPropertyChanged { // The dynamic entity representing the flight. public DynamicEntity Entity { get; }
// Backing fields for flight attributes. private string _flightNumber; private string _aircraft; private string _altitude; private string _speed; private string _heading; private string _status; private string _arrivalAirport; private bool _isExpanded;
// Initializes flight info with entity and subscribes to change events. public FlightInfo(DynamicEntity entity) { Entity = entity; UpdateAttributes(); Entity.DynamicEntityChanged += OnEntityChanged; }
public bool IsExpanded { get => _isExpanded; set { if (_isExpanded != value) { _isExpanded = value; OnPropertyChanged(); OnPropertyChanged(nameof(ToggleButtonText)); } } }
// Text for the toggle button based on expansion state. public string ToggleButtonText => IsExpanded ? "Hide Details" : "Show Details";
// Updates field value and raises property changed event if value differs. private bool SetField<T>(ref T field, T value, [CallerMemberName] string name = null) { if (EqualityComparer<T>.Default.Equals(field, value)) return false; field = value; OnPropertyChanged(name); return true; }
public string FlightNumber { get => _flightNumber; private set => SetField(ref _flightNumber, value); } public string Aircraft { get => _aircraft; private set => SetField(ref _aircraft, value); } public string Altitude { get => _altitude; private set => SetField(ref _altitude, value); } public string Speed { get => _speed; private set => SetField(ref _speed, value); } public string Heading { get => _heading; private set => SetField(ref _heading, value); } public string Status { get => _status; private set => SetField(ref _status, value); } public string ArrivalAirport { get => _arrivalAirport; private set => SetField(ref _arrivalAirport, value); }
// Retrieves attribute value from entity or returns default if not found. private string GetAttribute(string key, string defaultValue) { if (Entity?.Attributes != null && Entity.Attributes.TryGetValue(key, out var value)) return value?.ToString() ?? defaultValue; return defaultValue; }
// Formats numeric string to zero decimal places or returns original if not numeric. private string FormatNumber(string value) { if (double.TryParse(value, out double number)) return number.ToString("F0"); return value; }
// Refreshes all flight attribute properties from the entity. private void UpdateAttributes() { FlightNumber = GetAttribute("flight_number", "N/A"); Aircraft = GetAttribute("aircraft", "Unknown"); Altitude = FormatNumber(GetAttribute("altitude_feet", "0")); Speed = FormatNumber(GetAttribute("speed", "0")); Heading = FormatNumber(GetAttribute("heading", "0")); Status = GetAttribute("status", "Unknown"); ArrivalAirport = GetAttribute("arrival_airport", "N/A"); }
// Updates attributes when entity receives new observation data. private void OnEntityChanged(object sender, DynamicEntityChangedEventArgs e) { if (e.ReceivedObservation != null) { UpdateAttributes(); } }
// INotifyPropertyChanged implementation. public event PropertyChangedEventHandler PropertyChanged;
// Raises property changed event for data binding updates. protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); }}<?xml version="1.0" encoding="utf-8" ?><ContentPage x:Class="ArcGIS.Samples.QueryDynamicEntities.QueryDynamicEntities" xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:ArcGIS.Samples.QueryDynamicEntities" xmlns:esriUI="clr-namespace:Esri.ArcGISRuntime.Maui;assembly=Esri.ArcGISRuntime.Maui"> <Grid Style="{DynamicResource EsriSampleContainer}"> <esriUI:MapView x:Name="MyMapView" Style="{DynamicResource EsriSampleGeoView}" />
<!-- Query Controls --> <Border x:Name="QueryControlPanel" Margin="10" Style="{DynamicResource EsriSampleControlPanel}" VerticalOptions="Center"> <Border.HorizontalOptions> <OnPlatform x:TypeArguments="LayoutOptions"> <On Platform="iOS, Android" Value="Center" /> <On Platform="WinUI" Value="End" /> </OnPlatform> </Border.HorizontalOptions> <Picker x:Name="QueryDropdown" Title="Select Query" SelectedIndexChanged="OnQuerySelectionChanged" WidthRequest="280" /> </Border>
<!-- Query Results Panel --> <Border x:Name="ResultsPanel" Margin="10" IsVisible="False" MaximumHeightRequest="400" Style="{DynamicResource EsriSampleControlPanel}" VerticalOptions="Center" WidthRequest="350"> <Border.HorizontalOptions> <OnPlatform x:TypeArguments="LayoutOptions"> <On Platform="iOS, Android" Value="Center" /> <On Platform="WinUI" Value="End" /> </OnPlatform> </Border.HorizontalOptions> <Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="*" /> <RowDefinition Height="Auto" /> </Grid.RowDefinitions>
<Label Grid.Row="0" Margin="0,0,0,8" FontAttributes="Bold" FontSize="16" Text="Query Results" />
<Label x:Name="ResultsDescription" Grid.Row="1" Margin="0,0,0,8" FontAttributes="Italic" LineBreakMode="WordWrap" />
<CollectionView x:Name="ResultsList" Grid.Row="2" ItemSizingStrategy="MeasureAllItems" ItemsLayout="VerticalList" SelectionChanged="OnResultSelectionChanged" SelectionMode="Single" VerticalOptions="Fill"> <CollectionView.ItemTemplate> <DataTemplate x:DataType="local:FlightInfo"> <Border Margin="2" Padding="8" Style="{DynamicResource EsriSampleControlPanel}"> <VerticalStackLayout Spacing="4"> <Label FontAttributes="Bold" Text="{Binding FlightNumber}" /> <VerticalStackLayout x:Name="DetailsPanel" Margin="10,5,0,5" IsVisible="{Binding IsExpanded}" Spacing="2"> <Label FontSize="12"> <Label.FormattedText> <FormattedString> <Span FontAttributes="Bold" Text="Aircraft: " /> <Span Text="{Binding Aircraft}" /> </FormattedString> </Label.FormattedText> </Label> <Label FontSize="12"> <Label.FormattedText> <FormattedString> <Span FontAttributes="Bold" Text="Altitude: " /> <Span Text="{Binding Altitude}" /> <Span Text=" ft" /> </FormattedString> </Label.FormattedText> </Label> <Label FontSize="12"> <Label.FormattedText> <FormattedString> <Span FontAttributes="Bold" Text="Speed: " /> <Span Text="{Binding Speed}" /> <Span Text=" mph" /> </FormattedString> </Label.FormattedText> </Label> <Label FontSize="12"> <Label.FormattedText> <FormattedString> <Span FontAttributes="Bold" Text="Heading: " /> <Span Text="{Binding Heading}" /> <Span Text="°" /> </FormattedString> </Label.FormattedText> </Label> <Label FontSize="12"> <Label.FormattedText> <FormattedString> <Span FontAttributes="Bold" Text="Status: " /> <Span Text="{Binding Status}" /> </FormattedString> </Label.FormattedText> </Label> <Label FontSize="12"> <Label.FormattedText> <FormattedString> <Span FontAttributes="Bold" Text="Arrival: " /> <Span Text="{Binding ArrivalAirport}" /> </FormattedString> </Label.FormattedText> </Label> </VerticalStackLayout> <Button Padding="4,1" Clicked="OnToggleDetails" CommandParameter="{Binding .}" CornerRadius="4" FontSize="10" HeightRequest="26" Text="{Binding ToggleButtonText}" /> </VerticalStackLayout> </Border> </DataTemplate> </CollectionView.ItemTemplate> </CollectionView>
<Button Grid.Row="3" Margin="0,8,0,0" Padding="12,4" Clicked="OnCloseResults" HorizontalOptions="End" Text="Close" /> </Grid> </Border>
<!-- Flight Number Input Dialog --> <Border x:Name="FlightNumberDialog" Margin="20" HorizontalOptions="Center" IsVisible="False" Style="{DynamicResource EsriSampleControlPanel}" VerticalOptions="Center" WidthRequest="300"> <VerticalStackLayout Spacing="8"> <Label Margin="0,0,0,8" Text="Enter Flight Number" /> <Entry x:Name="FlightNumberInput" BackgroundColor="White" Completed="OnFlightNumberQuery" TextColor="Black" /> <Label Margin="0,4,0,0" FontAttributes="Italic" FontSize="11" Text="Example: Flight_1107" TextColor="Gray" /> <HorizontalStackLayout Margin="0,8,0,0" HorizontalOptions="End" Spacing="8"> <Button Padding="12,4" Clicked="OnFlightNumberQuery" Text="Query" /> <Button Padding="12,4" Clicked="OnFlightNumberCancel" Text="Cancel" /> </HorizontalStackLayout> </VerticalStackLayout> </Border> </Grid></ContentPage>// Copyright 2025 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 ArcGIS.Samples.Managers;using Esri.ArcGISRuntime.ArcGISServices;using Esri.ArcGISRuntime.Data;using Esri.ArcGISRuntime.Geometry;using Esri.ArcGISRuntime.Mapping;using Esri.ArcGISRuntime.Mapping.Labeling;using Esri.ArcGISRuntime.RealTime;using Esri.ArcGISRuntime.Symbology;using Esri.ArcGISRuntime.UI;using System.Collections.ObjectModel;using Map = Esri.ArcGISRuntime.Mapping.Map;
namespace ArcGIS.Samples.QueryDynamicEntities{ [ArcGIS.Samples.Shared.Attributes.Sample( name: "Query dynamic entities", category: "Search", description: "Find dynamic entities from a data source that match a query.", instructions: "Tap the \"Query Flights\" button and select a query to perform from the menu. Once the query is complete, a list of the resulting flights will be displayed. Tap on a flight to see its latest attributes in real-time.", tags: new[] { "data", "dynamic", "entity", "live", "query", "real-time", "search", "stream", "track" })] [ArcGIS.Samples.Shared.Attributes.OfflineData("c78e297e99ad4572a48cdcd0b54bed30")] public partial class QueryDynamicEntities : ContentPage { private CustomStreamService _dynamicEntityDataSource; private DynamicEntityLayer _dynamicEntityLayer; private GraphicsOverlay _bufferGraphicsOverlay; private Geometry _phoenixAirportBuffer; private ObservableCollection<FlightInfo> _queryResults; private readonly MapPoint _phoenixAirport = new MapPoint(-112.0101, 33.4352, SpatialReferences.Wgs84); private List<string> _queryOptions;
public QueryDynamicEntities() { InitializeComponent(); _ = Initialize(); }
private async Task Initialize() { try { // Create the map with a basemap and initial viewpoint. MyMapView.Map = new Map(BasemapStyle.ArcGISTopographic); await MyMapView.SetViewpointAsync(new Viewpoint(_phoenixAirport, 400000));
// Create and add a graphics overlay for the buffer around Phoenix Airport (PHX). _bufferGraphicsOverlay = new GraphicsOverlay(); MyMapView.GraphicsOverlays.Add(_bufferGraphicsOverlay);
_phoenixAirportBuffer = GeometryEngine.BufferGeodetic( _phoenixAirport, 15, LinearUnits.Miles, double.NaN, GeodeticCurveType.Geodesic);
// Create a semi-transparent fill symbol for the buffer area. var bufferSymbol = new SimpleFillSymbol( SimpleFillSymbolStyle.Solid, System.Drawing.Color.FromArgb(40, 255, 0, 0), new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, System.Drawing.Color.Black, 1));
// Add the buffer graphic to the overlay and hide it initially. _bufferGraphicsOverlay.Graphics.Add(new Graphic(_phoenixAirportBuffer, bufferSymbol)); _bufferGraphicsOverlay.IsVisible = false;
// Initialize the collection for query results and bind it to the results list. _queryResults = new ObservableCollection<FlightInfo>(); ResultsList.ItemsSource = _queryResults;
// Set up the query options in the dropdown menu. _queryOptions = new List<string> { "Within 15 Miles of PHX", "Arriving in PHX", "With Flight Number" };
// Bind the query options to the dropdown and set initial visibility states. QueryDropdown.ItemsSource = _queryOptions; QueryDropdown.SelectedIndex = -1; ResultsPanel.IsVisible = false; FlightNumberDialog.IsVisible = false; QueryDropdown.IsVisible = true;
// Create and configure the dynamic entity data source and layer. await SetupDynamicEntityDataSource(); } catch (Exception ex) { await DisplayAlert("Error", $"Error initializing sample: {ex.Message}", "OK"); } }
// Creates and configures the dynamic entity data source and layer for real-time flight tracking. private async Task SetupDynamicEntityDataSource() { try { // Define the fields expected in the dynamic entity data source. var fields = new List<Field> { new Field(FieldType.Text, "flight_number", "", 50), new Field(FieldType.Text, "aircraft", "", 50), new Field(FieldType.Float64, "altitude_feet", "", 0), new Field(FieldType.Text, "arrival_airport", "", 10), new Field(FieldType.Float64, "heading", "", 0), new Field(FieldType.Float64, "speed", "", 0), new Field(FieldType.Text, "status", "", 50) };
// Create the data source info with the unique track ID field and spatial reference. var dataSourceInfo = new DynamicEntityDataSourceInfo("flight_number", fields) { SpatialReference = SpatialReferences.Wgs84 };
// Get the path to the JSON data file. string dataPath = DataManager.GetDataFolder("c78e297e99ad4572a48cdcd0b54bed30", "phx_air_traffic.json");
// Initialize the custom stream service with the data source info and file path. _dynamicEntityDataSource = new CustomStreamService(dataSourceInfo, dataPath, TimeSpan.FromMilliseconds(100));
// Create the dynamic entity layer with the data source and configure its display properties. _dynamicEntityLayer = new DynamicEntityLayer(_dynamicEntityDataSource) { TrackDisplayProperties = { ShowPreviousObservations = true, ShowTrackLine = true, MaximumObservations = 20 } };
// Label each dynamic entity with its flight number above the point. var labelDefinition = new LabelDefinition( new SimpleLabelExpression("[flight_number]"), new TextSymbol { Color = System.Drawing.Color.Red, Size = 12, HaloColor = System.Drawing.Color.White, HaloWidth = 2 }) { Placement = LabelingPlacement.PointAboveCenter };
_dynamicEntityLayer.LabelDefinitions.Add(labelDefinition); _dynamicEntityLayer.LabelsEnabled = true; MyMapView.Map.OperationalLayers.Add(_dynamicEntityLayer); await _dynamicEntityDataSource.ConnectAsync(); } catch (Exception ex) { await DisplayAlert("Error", $"Error setting up data source: {ex.Message}", "OK"); } }
// Handles query selection from dropdown and initiates appropriate query type. private async void OnQuerySelectionChanged(object sender, EventArgs e) { if (QueryDropdown.SelectedIndex < 0) return;
var selectedOption = QueryDropdown.SelectedItem as string; if (string.IsNullOrEmpty(selectedOption)) return;
var queryType = selectedOption switch { "Within 15 Miles of PHX" => "QueryGeometry", "Arriving in PHX" => "QueryAttributes", "With Flight Number" => "QueryTrackId", _ => null };
if (string.IsNullOrEmpty(queryType)) return;
if (queryType == "QueryTrackId") { QueryControlPanel.IsVisible = false; FlightNumberDialog.IsVisible = true; FlightNumberInput.Focus(); } else { await PerformQuery(queryType); } }
// Processes flight number input and executes track ID query. private async void OnFlightNumberQuery(object sender, EventArgs e) { var flightNumber = FlightNumberInput.Text?.Trim(); if (string.IsNullOrWhiteSpace(flightNumber)) { await DisplayAlert("Input Required", "Please enter a flight number.", "OK"); return; }
FlightNumberDialog.IsVisible = false; await PerformQuery("QueryTrackId", flightNumber); FlightNumberInput.Text = string.Empty; }
// Cancels flight number input and returns to query selection. private void OnFlightNumberCancel(object sender, EventArgs e) { FlightNumberDialog.IsVisible = false; FlightNumberInput.Text = string.Empty; QueryDropdown.SelectedIndex = -1; QueryControlPanel.IsVisible = true; }
// Toggles visibility of flight detail information in the results list. private void OnToggleDetails(object sender, EventArgs e) { if (sender is Button button && button.BindingContext is FlightInfo flightInfo) { flightInfo.IsExpanded = !flightInfo.IsExpanded; } }
// Queries dynamic entities that intersect with the specified geometry and returns the results of the query. private async Task<IReadOnlyList<DynamicEntity>> QueryDynamicEntitiesAsync(Geometry geometry) { // Sets the parameters' geometry and spatial relationship to query within the buffer. var parameters = new DynamicEntityQueryParameters { Geometry = geometry, SpatialRelationship = SpatialRelationship.Intersects };
// Performs a dynamic entities query on the data source. var queryResult = await _dynamicEntityDataSource.QueryDynamicEntitiesAsync(parameters);
// Gets the dynamic entities from the query result. return queryResult?.ToList(); }
// Queries dynamic entities that match the specified attribute where clause and returns the results of the query. private async Task<IReadOnlyList<DynamicEntity>> QueryDynamicEntitiesAsync(string whereClause) { // Sets the parameters' where clause to query the entities' attributes. var parameters = new DynamicEntityQueryParameters { WhereClause = whereClause };
// Performs a dynamic entities query on the data source. var queryResult = await _dynamicEntityDataSource.QueryDynamicEntitiesAsync(parameters);
// Gets the dynamic entities from the query result. return queryResult?.ToList(); }
// Queries dynamic entities with the specified track IDs and returns the results of the query. private async Task<IReadOnlyList<DynamicEntity>> QueryDynamicEntitiesAsync(IEnumerable<string> trackIds) { // Performs a dynamic entities query on the data source. // Use this method when querying only by track IDs. var queryResult = await _dynamicEntityDataSource.QueryDynamicEntitiesAsync(trackIds);
// Gets the dynamic entities from the query result. return queryResult?.ToList(); }
// Executes the specified query type on the data source private async Task PerformQuery(string queryType, string flightNumber = null) { _queryResults.Clear(); _dynamicEntityLayer?.ClearSelection(); _bufferGraphicsOverlay.IsVisible = false; ResultsPanel.IsVisible = true; QueryControlPanel.IsVisible = false;
// Holds the dynamic entities returned from the query. IReadOnlyList<DynamicEntity> results = Array.Empty<DynamicEntity>();
switch (queryType) { case "QueryGeometry": results = await QueryDynamicEntitiesAsync(_phoenixAirportBuffer); // Shows the buffer graphic when querying by geometry. _bufferGraphicsOverlay.IsVisible = true; ResultsDescription.Text = "Flights within 15 miles of PHX"; break;
case "QueryAttributes": results = await QueryDynamicEntitiesAsync("status = 'In flight' AND arrival_airport = 'PHX'"); ResultsDescription.Text = "Flights arriving in PHX"; break;
case "QueryTrackId": if (!string.IsNullOrWhiteSpace(flightNumber)) { results = await QueryDynamicEntitiesAsync(new[] { flightNumber }); ResultsDescription.Text = $"Flight {flightNumber}"; } break; }
await Task.Yield();
foreach (var result in results) { _dynamicEntityLayer.SelectDynamicEntity(result); _queryResults.Add(new FlightInfo(result)); }
ResultsPanel.IsVisible = true; }
// Centers the map view on the selected flight's current position. private async void OnResultSelectionChanged(object sender, SelectionChangedEventArgs e) { if (e.CurrentSelection.FirstOrDefault() is FlightInfo flight && flight.Entity != null) { var latestObs = flight.Entity.GetLatestObservation(); if (latestObs?.Geometry is MapPoint point) { await MyMapView.SetViewpointCenterAsync(point, 50000); } } }
// Closes the results panel and resets the UI to the initial state. private void OnCloseResults(object sender, EventArgs e) { ResultsPanel.IsVisible = false; QueryControlPanel.IsVisible = true;
_queryResults.Clear();
if (_dynamicEntityLayer != null) { _dynamicEntityLayer.ClearSelection(); }
_bufferGraphicsOverlay.IsVisible = false; QueryDropdown.SelectedIndex = -1; } }}