Skip to content
View on GitHub

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

Image of Query dynamic entities sample

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

  1. Create a DynamicEntityDataSource to stream dynamic entity events.
  2. Create DynamicEntityQueryParameters and set its properties to specify the parameters for the query:
    1. To spatially filter results, set the geometry and spatialRelationship. The spatial relationship is intersects by default.
    2. To query entities with certain attribute values, set the whereClause.
    3. To get entities with specific track IDs, modify the trackIDs collection.
  3. To perform a dynamic entities query, call DynamicEntityDataSource.queryDynamicEntities(using:) passing in the parameters.
  4. When complete, get the dynamic entities from the result using DynamicEntityQueryResult.entities().
  5. Use DynamicEntity.changes to get the entities' change notifications.
  6. Get the new observation from the resulting DynamicEntityChangedInfo objects using receivedObservation and use dynamicEntityWasPurged to determine whether a dynamic entity has been purged.

Relevant API

  • DynamicEntity
  • DynamicEntityChangedInfo
  • DynamicEntityDataSource
  • DynamicEntityLayer
  • DynamicEntityObservation
  • DynamicEntityObservationInfo
  • 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

QueryDynamicEntitiesView.swiftQueryDynamicEntitiesView.swiftQueryDynamicEntitiesView.Model.swift
Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
// 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
//
//   https://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 ArcGIS
import SwiftUI

struct QueryDynamicEntitiesView: View {
    /// The view model for the sample.
    @State private var model = Model()

    /// A Boolean value indicating whether the alert for entering a flight number is showing.
    @State private var flightNumberAlertIsShowing = false

    /// The text entered into the flight number alert's text field.
    @State private var flightNumber = ""

    /// The type of query currently being performed.
    @State private var selectedQueryType: QueryType?

    /// The result of a dynamic entities query operation.
    @State private var queryResult: Result<[DynamicEntity], any Error>?

    var body: some View {
        MapView(map: model.map, graphicsOverlays: [model.graphicsOverlay])
            .contentInsets(.init(top: 0, leading: 0, bottom: 250, trailing: 0))
            .toolbar {
                ToolbarItemGroup(placement: .bottomBar) {
                    Spacer()
                    Menu("Query Flights") {
                        Button("Within 15 Miles of PHX", systemImage: "dot.circle") {
                            selectedQueryType = .geometry
                        }
                        Button("Arriving in PHX", systemImage: "airplane.arrival") {
                            selectedQueryType = .attributes
                        }
                        Button("With Flight Number", systemImage: "magnifyingglass") {
                            flightNumberAlertIsShowing = true
                        }
                    }
                    .menuOrder(.fixed)
                    .alert("Enter a Flight Number to Query", isPresented: $flightNumberAlertIsShowing) {
                        TextField("Flight Number", text: $flightNumber, prompt: .init("Flight_396"))

                        Button("Done") {
                            selectedQueryType = .trackID(flightNumber)
                        }
                        .disabled(flightNumber.isEmpty)

                        Button("Cancel", role: .cancel, action: {})
                    }
                    .task(id: selectedQueryType) {
                        guard let selectedQueryType else { return }
                        queryResult = await model.queryDynamicEntities(type: selectedQueryType)
                    }
                    .popover(item: $selectedQueryType) { queryType in
                        QueryResultView(result: queryResult, type: queryType)
                            .onDisappear(perform: model.resetDisplay)
                            .presentationDetents([.fraction(0.5), .large])
                            .frame(idealWidth: 320, idealHeight: 380)
                    }
                    Spacer()
                }
            }
    }
}

private extension QueryDynamicEntitiesView {
    /// A view that displays the result of a dynamic entities query operation.
    struct QueryResultView: View {
        /// The result of the dynamic entities query operation.
        let result: Result<[DynamicEntity], any Error>?

        /// The type of query that was performed.
        let type: QueryType

        /// The action to dismiss the view.
        @Environment(\.dismiss) private var dismiss

        var body: some View {
            NavigationStack {
                Group {
                    switch result {
                    case .success(let entities):
                        if !entities.isEmpty {
                            List {
                                Section(type.resultLabel) {
                                    ForEach(entities, id: \.id) { entity in
                                        DynamicEntityObservationView(entity: entity)
                                    }
                                }
                            }
                        } else {
                            ContentUnavailableView(
                                "No Results",
                                systemImage: "airplane",
                                description: .init("There are no flights to display for this query.")
                            )
                        }
                    case .failure(let error):
                        ContentUnavailableView(
                            "Error",
                            systemImage: "exclamationmark.triangle",
                            description: .init(String(reflecting: error))
                        )
                    case nil:
                        ProgressView("Querying dynamic entities")
                    }
                }
                .navigationTitle("Query Results")
                .navigationBarTitleDisplayMode(.inline)
                .toolbar {
                    ToolbarItem(placement: .confirmationAction) {
                        Button("Done") { dismiss() }
                    }
                }
            }
        }
    }

    /// A view that displays the latest observation of a dynamic entity.
    struct DynamicEntityObservationView: View {
        /// The dynamic entity to observe.
        let entity: DynamicEntity

        /// The latest observation's attributes to display.
        @State private var attributes: [String: any Sendable] = [:]

        /// A Boolean value indicating whether the disclosure group is expanded.
        @State private var isExpanded = false

        var body: some View {
            let flightNumber = entity.attributes["flight_number"] as? String
            DisclosureGroup(flightNumber ?? "N/A", isExpanded: $isExpanded) {
                let attributes = attributes.sorted(by: { $0.key < $1.key })
                ForEach(attributes, id: \.key) { name, value in
                    let label = PlaneAttributeKey(rawValue: name)?.label ?? name
                    if let string = value as? String {
                        LabeledContent(label, value: string)
                    } else if let double = value as? Double {
                        LabeledContent(
                            label,
                            value: double,
                            format: .number.precision(.fractionLength(0...2))
                        )
                    }
                }
            }
            .task {
                attributes = entity.latestObservation?.attributes ?? [:]

                for await changedInfo in entity.changes {
                    attributes = changedInfo.receivedObservation?.attributes ?? [:]
                }
            }
        }
    }
}

private extension QueryDynamicEntitiesView.PlaneAttributeKey {
    /// A human-readable label for the attribute.
    var label: String {
        switch self {
        case .aircraft: "Aircraft"
        case .altitudeFeet: "Altitude (ft)"
        case .arrivalAirport: "Arrival Airport"
        case .flightNumber: "Flight Number"
        case .heading: "Heading"
        case .speed: "Speed"
        case .status: "Status"
        }
    }
}

private extension QueryDynamicEntitiesView.QueryType {
    /// The human-readable text describing the query results.
    var resultLabel: String {
        switch self {
        case .geometry: "Flights within 15 miles of PHX"
        case .attributes: "Flights arriving in PHX"
        case .trackID(let trackID): "Flights matching number: \(trackID)"
        }
    }
}

Your browser is no longer supported. Please upgrade your browser for the best experience. See our browser deprecation post for more details.