Skip to content
View on GitHubSample viewer app

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, use DynamicEntityDataSource.queryDynamicEntities(parameters) to query with multiple criteria (such as track IDs, spatial, and/or attribute filters), or use DynamicEntityDataSource.queryDynamicEntities(trackIds) if you want to query only by track IDs.
  4. When complete, get the dynamic entities from the result using DynamicEntityQueryResult.entities().
  5. Use DynamicEntity.dynamicEntityChangedEvent 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

QueryDynamicEntitiesViewModel.ktQueryDynamicEntitiesViewModel.ktDownloadActivity.ktMainActivity.ktQueryDynamicEntitiesScreen.kt
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
/* Copyright 2026 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.
 *
 */

package com.esri.arcgismaps.sample.querydynamicentities.components

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.arcgismaps.Color
import com.arcgismaps.arcgisservices.LabelingPlacement
import com.arcgismaps.data.Field
import com.arcgismaps.data.FieldType
import com.arcgismaps.data.SpatialRelationship
import com.arcgismaps.geometry.GeodeticCurveType
import com.arcgismaps.geometry.Geometry
import com.arcgismaps.geometry.GeometryEngine
import com.arcgismaps.geometry.LinearUnit
import com.arcgismaps.geometry.Point
import com.arcgismaps.geometry.SpatialReference
import com.arcgismaps.mapping.ArcGISMap
import com.arcgismaps.mapping.BasemapStyle
import com.arcgismaps.mapping.Viewpoint
import com.arcgismaps.mapping.labeling.LabelDefinition
import com.arcgismaps.mapping.labeling.SimpleLabelExpression
import com.arcgismaps.mapping.layers.DynamicEntityLayer
import com.arcgismaps.mapping.symbology.SimpleFillSymbol
import com.arcgismaps.mapping.symbology.SimpleFillSymbolStyle
import com.arcgismaps.mapping.symbology.SimpleLineSymbol
import com.arcgismaps.mapping.symbology.SimpleLineSymbolStyle
import com.arcgismaps.mapping.symbology.TextSymbol
import com.arcgismaps.mapping.view.Graphic
import com.arcgismaps.mapping.view.GraphicsOverlay
import com.arcgismaps.realtime.CustomDynamicEntityDataSource
import com.arcgismaps.realtime.DynamicEntity
import com.arcgismaps.realtime.DynamicEntityDataSourceInfo
import com.arcgismaps.realtime.DynamicEntityQueryParameters
import com.esri.arcgismaps.sample.sampleslib.components.MessageDialogViewModel
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlin.math.cos
import kotlin.math.sin

class QueryDynamicEntitiesViewModel(application: Application) : AndroidViewModel(application) {

    // Map centered on Phoenix Sky Harbor International Airport
    val arcGISMap = ArcGISMap(BasemapStyle.ArcGISTopographic).apply {
        initialViewpoint = Viewpoint(center = phoenixAirport, scale = 1_266_500.0)
    }

    // Graphics overlay to display the 15-mile buffer around the airport
    val graphicsOverlay = GraphicsOverlay()
    private val bufferGraphic = Graphic(
        symbol = SimpleFillSymbol(
            style = SimpleFillSymbolStyle.Solid,
            color = Color.fromRgba(255, 0, 0, 64),
            outline = SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.black, 1f)
        )
    )

    // Simulated plane feed and dynamic entity layer
    private val planeFeedProvider = PlaneFeedProvider()
    private val dynamicEntityDataSource = CustomDynamicEntityDataSource(planeFeedProvider)
    private val dynamicEntityLayer = DynamicEntityLayer(dynamicEntityDataSource).apply {
        trackDisplayProperties.apply {
            showPreviousObservations = true
            showTrackLine = true
            maximumObservations = 20
        }

        // Display flight numbers above entities
        val labelDefinition = LabelDefinition(
            labelExpression = SimpleLabelExpression("[flight_number]"),
            textSymbol = TextSymbol().apply {
                color = Color.red
                size = 12f
            }
        ).apply { placement = LabelingPlacement.PointAboveCenter }
        labelDefinitions.add(labelDefinition)
        labelsEnabled = true
    }

    // Message dialog for error handling
    val messageDialogVM = MessageDialogViewModel()

    // Query UI states
    private val _isQueryRunning = MutableStateFlow(false)
    val isQueryRunning = _isQueryRunning.asStateFlow()

    private val _queryResultEntities = MutableStateFlow<List<DynamicEntity>>(emptyList())
    val queryResultEntities = _queryResultEntities.asStateFlow()

    private val _resultLabel = MutableStateFlow("")
    val resultLabel = _resultLabel.asStateFlow()

    init {
        // Add layer to the map
        arcGISMap.operationalLayers.add(dynamicEntityLayer)

        // Prepare buffer graphic; keep overlay hidden until used
        graphicsOverlay.graphics.add(bufferGraphic)
        graphicsOverlay.isVisible = false

        // Connect the data source to start streaming observations
        viewModelScope.launch {
            dynamicEntityDataSource.connect().onFailure {
                messageDialogVM.showMessageDialog(
                    title = "Failed to connect data source",
                    description = it.message.toString()
                )
            }
        }
    }

    // Query: Flights within 15 miles of PHX
    fun queryFlightsWithinPhoenixBuffer() {
        viewModelScope.launch {
            _isQueryRunning.value = true
            val buffer = createPhoenixAirportBuffer()
            bufferGraphic.geometry = buffer
            graphicsOverlay.isVisible = true

            val parameters = DynamicEntityQueryParameters().apply {
                geometry = buffer
                spatialRelationship = SpatialRelationship.Intersects
            }

            val queryResult = dynamicEntityDataSource.queryDynamicEntities(parameters)
            queryResult.onSuccess { result ->
                val entities = result.toList()
                dynamicEntityLayer.clearSelection()
                dynamicEntityLayer.selectDynamicEntities(entities)
                _queryResultEntities.value = entities
                _resultLabel.value = "Flights within 15 miles of PHX"
            }.onFailure { error ->
                messageDialogVM.showMessageDialog(
                    title = "Query failed",
                    description = error.message.toString()
                )
            }
            _isQueryRunning.value = false
        }
    }

    // Query: Flights arriving in PHX (attribute query)
    fun queryFlightsArrivingInPHX() {
        viewModelScope.launch {
            _isQueryRunning.value = true
            graphicsOverlay.isVisible = false

            val parameters = DynamicEntityQueryParameters().apply {
                whereClause = "status = 'In flight' AND arrival_airport = 'PHX'"
            }

            val queryResult = dynamicEntityDataSource.queryDynamicEntities(parameters)
            queryResult.onSuccess { result ->
                val entities = result.toList()
                dynamicEntityLayer.clearSelection()
                dynamicEntityLayer.selectDynamicEntities(entities)
                _queryResultEntities.value = entities
                _resultLabel.value = "Flights arriving in PHX"
            }.onFailure { error ->
                messageDialogVM.showMessageDialog(
                    title = "Query failed",
                    description = error.message.toString()
                )
            }
            _isQueryRunning.value = false
        }
    }

    // Query: Flights with a specific flight number (trackId)
    fun queryFlightsWithNumber(flightNumber: String) {
        viewModelScope.launch {
            _isQueryRunning.value = true
            graphicsOverlay.isVisible = false

            val parameters = DynamicEntityQueryParameters().apply {
                trackIds.add(flightNumber)
            }

            val queryResult = dynamicEntityDataSource.queryDynamicEntities(parameters)
            queryResult.onSuccess { result ->
                val entities = result.toList()
                dynamicEntityLayer.clearSelection()
                dynamicEntityLayer.selectDynamicEntities(entities)
                _queryResultEntities.value = entities
                _resultLabel.value = "Flights matching number: $flightNumber"
            }.onFailure { error ->
                messageDialogVM.showMessageDialog(
                    title = "Query failed",
                    description = error.message.toString()
                )
            }
            _isQueryRunning.value = false
        }
    }

    // Reset selection and overlay
    fun resetDisplay() {
        _queryResultEntities.value = emptyList()
        dynamicEntityLayer.clearSelection()
        graphicsOverlay.isVisible = false
        _resultLabel.value = ""
    }

    // Create a 15-mile geodetic buffer around PHX
    private fun createPhoenixAirportBuffer(): Geometry {
        return GeometryEngine.bufferGeodeticOrNull(
            geometry = phoenixAirport,
            distance = 15.0,
            distanceUnit = LinearUnit.miles,
            maxDeviation = Double.NaN,
            curveType = GeodeticCurveType.Geodesic
        ) ?: phoenixAirport
    }

    companion object {
        // Phoenix Sky Harbor Intl Airport (lon, lat) in WGS84
        private val phoenixAirport = Point(
            -112.0101,
            33.4352,
            SpatialReference.wgs84()
        )
    }
}

// Simulated plane feed provider that emits observations near Phoenix
private class PlaneFeedProvider : CustomDynamicEntityDataSource.EntityFeedProvider {

    private val scope = CoroutineScope(Dispatchers.Default)

    private val _feed = MutableSharedFlow<CustomDynamicEntityDataSource.FeedEvent>(
        extraBufferCapacity = Int.MAX_VALUE,
        onBufferOverflow = BufferOverflow.DROP_OLDEST
    )
    override val feed: SharedFlow<CustomDynamicEntityDataSource.FeedEvent> = _feed.asSharedFlow()

    private var feedJob: Job? = null

    // Schema for attributes used in the sample
    private val schema: List<Field> by lazy {
        listOf(
            Field(FieldType.Text, "flight_number", "", 128),
            Field(FieldType.Text, "aircraft", "", 128),
            Field(FieldType.Float64, "altitude_feet", "", 8),
            Field(FieldType.Text, "arrival_airport", "", 32),
            Field(FieldType.Float64, "heading", "", 8),
            Field(FieldType.Float64, "speed", "", 8),
            Field(FieldType.Text, "status", "", 64)
        )
    }

    override suspend fun onLoad(): DynamicEntityDataSourceInfo {
        return DynamicEntityDataSourceInfo(
            entityIdFieldName = "flight_number",
            fields = schema
        ).apply { spatialReference = SpatialReference.wgs84() }
    }

    override suspend fun onConnect() {
        startEmitting()
    }

    override suspend fun onDisconnect() {
        feedJob?.cancelAndJoin()
        feedJob = null
    }

    private fun startEmitting() {
        val flights = buildList { repeat(20) { add("Flight_${300 + it}") } }
        val phoenix = Point(-112.0101, 33.4352, SpatialReference.wgs84())
        val radiusDegrees = 0.18 // ~12-13 miles radius
        var tick = 0

        feedJob = scope.launch(Dispatchers.IO) {
            try {
                while (true) {
                    tick++
                    flights.forEachIndexed { idx, flightId ->
                        val angleDeg = (tick * 6 + idx * 18) % 360
                        val angleRad = Math.toRadians(angleDeg.toDouble())
                        val lon = phoenix.x + radiusDegrees * cos(angleRad)
                        val lat = phoenix.y + radiusDegrees * sin(angleRad)
                        val point = Point(lon, lat, SpatialReference.wgs84())

                        val attributes = mapOf(
                            "flight_number" to flightId,
                            "aircraft" to listOf("A320", "B737", "B738", "E175", "A321")[idx % 5],
                            "altitude_feet" to (14000..36000).random().toDouble(),
                            "arrival_airport" to "PHX",
                            "heading" to (angleDeg.toDouble()),
                            "speed" to (350..520).random().toDouble(),
                            "status" to "In flight"
                        )

                        _feed.tryEmit(
                            CustomDynamicEntityDataSource.FeedEvent.NewObservation(
                                geometry = point,
                                attributes = attributes
                            )
                        )
                    }
                    delay(1000)
                }
            } catch (e: Exception) {
                if (e is CancellationException) throw e
                withContext(NonCancellable) {
                    _feed.tryEmit(
                        CustomDynamicEntityDataSource.FeedEvent.ConnectionFailure(
                            e,
                            true
                        )
                    )
                }
            }
        }
    }
}

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