Display data from an ArcGIS stream service using a dynamic entity layer.

Use case
A stream service is a type of service provided by ArcGIS Velocity and GeoEvent Server that allows clients to receive a stream of data observations via a web socket. ArcGIS Maps SDK for Kotlin allows you to connect to a stream service and manage the information as dynamic entities and display them in a dynamic entity layer. Displaying information from feeds such as a stream service is important in applications like dashboards where users need to visualize and track updates of real-world objects in real-time.
Use ArcGISStreamService to manage the connection to the stream service and purge options to manage how much data is stored and maintained by the application. The dynamic entity layer will display the latest received observation, and you can set track display properties to determine how to display historical information for each dynamic entity. This includes the number of previous observations to show, whether to display track lines in-between previous observations, and setting renderers.
How to use the sample
Use the controls to connect to or disconnect from the stream service, modify display properties in the dynamic entity layer, and purge all observations from the application.
How it works
- Create an
ArcGIStreamServiceusing aUrl. - Set a
DynamicEntityFilteron the stream service to limit the amount of data coming from the server. - Set the
MaximumDurationproperty of the stream servicePurgeOptionsto limit the amount of data managed by the application. - Create a
DynamicEntityLayerusing the stream service. - Update values in the layer’s
TrackDisplayPropertiesto customize the layer’s appearance. - Add the
DynamicEntityLayerto the map.
Relevant API
- ArcGISStreamService
- DynamicEntity
- DynamicEntityFilter
- DynamicEntityLayer
- DynamicEntityPurgeOptions
- TrackDisplayProperties
About the data
This sample uses a stream service that simulates live data coming from snowplows near Sandy, Utah. There are multiple vehicle types and multiple agencies operating the snowplows.
Additional information
This sample uses the GeoView-Compose Toolkit module to be able to implement a composable MapView. More information about dynamic entities can be found in the guide documentation.
Tags
data, dynamic, entity, geoview-compose, live, purge, real-time, service, stream, toolkit, track
Sample Code
/* 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. * */
package com.esri.arcgismaps.sample.adddynamicentitylayer
import android.os.Bundleimport androidx.activity.ComponentActivityimport androidx.activity.compose.setContentimport androidx.activity.enableEdgeToEdgeimport androidx.compose.material3.MaterialThemeimport androidx.compose.material3.Surfaceimport androidx.compose.runtime.Composableimport com.arcgismaps.ApiKeyimport com.arcgismaps.ArcGISEnvironmentimport com.esri.arcgismaps.sample.sampleslib.theme.SampleAppThemeimport com.esri.arcgismaps.sample.adddynamicentitylayer.screens.MainScreen
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // authentication with an API key or named user is // required to access basemaps and other location services ArcGISEnvironment.apiKey = ApiKey.create(BuildConfig.ACCESS_TOKEN) enableEdgeToEdge() setContent { SampleAppTheme { AddDynamicEntityLayerApp() } } }
@Composable private fun AddDynamicEntityLayerApp() { Surface( color = MaterialTheme.colorScheme.background ) { MainScreen( sampleName = getString(R.string.add_dynamic_entity_layer_app_name) ) } }}/* 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. * */
package com.esri.arcgismaps.sample.adddynamicentitylayer.components
import android.content.res.Configurationimport androidx.compose.foundation.BorderStrokeimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.layout.Arrangementimport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.Rowimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.shape.RoundedCornerShapeimport androidx.compose.material3.HorizontalDividerimport androidx.compose.material3.MaterialThemeimport androidx.compose.material3.Sliderimport androidx.compose.material3.Surfaceimport androidx.compose.material3.Switchimport androidx.compose.material3.Textimport androidx.compose.material3.TextButtonimport androidx.compose.runtime.Composableimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Alignment.Companion.CenterHorizontallyimport androidx.compose.ui.Modifierimport androidx.compose.ui.tooling.preview.Previewimport androidx.compose.ui.unit.dpimport com.esri.arcgismaps.sample.sampleslib.theme.SampleAppThemeimport com.esri.arcgismaps.sample.sampleslib.theme.SampleTypographyimport kotlin.math.roundToInt
/** * Composable component to display Dynamic Entity Layer Settings */@Composablefun DynamicEntityLayerProperties( onTrackLineVisibilityChanged: (Boolean) -> Unit = { }, onPrevObservationsVisibilityChanged: (Boolean) -> Unit = { }, onObservationsChanged: (Float) -> Unit = { }, onPurgeAllObservations: () -> Unit = { }, isTrackLineVisible: Boolean, isPrevObservationsVisible: Boolean, observationsPerTrack: Float, onDismiss: () -> Unit = { }) { Column(Modifier.background(MaterialTheme.colorScheme.background)) { Row( modifier = Modifier.fillMaxWidth().padding(20.dp, 20.dp, 20.dp, 0.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween ) { Text( style = SampleTypography.titleMedium, text = "Dynamic Entity Settings", color = MaterialTheme.colorScheme.primary ) TextButton( onClick = onDismiss ) { Text(text = "Done") } }
Surface( modifier = Modifier.padding(20.dp), tonalElevation = 1.dp, shape = RoundedCornerShape(20.dp), border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant) ) { Column( modifier = Modifier.padding(14.dp) ) { Row( modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween ) { Text( text = "Track Lines", style = SampleTypography.bodyLarge ) Switch( checked = isTrackLineVisible, onCheckedChange = { onTrackLineVisibilityChanged(it) } ) } HorizontalDivider(thickness = 0.5.dp) Row( modifier = Modifier .fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween ) { Text( text = "Previous Observations", style = SampleTypography.bodyLarge ) Switch( checked = isPrevObservationsVisible, onCheckedChange = { onPrevObservationsVisibilityChanged(it) } ) } } }
Surface( modifier = Modifier.padding(20.dp), tonalElevation = 1.dp, shape = RoundedCornerShape(20.dp), border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant) ) { Column( modifier = Modifier.padding(14.dp) ) { Column { Row { Text( modifier = Modifier.weight(12f), text = "Observations per track", ) Text( modifier = Modifier.weight(1f), text = observationsPerTrack.roundToInt().toString() ) } Slider( value = observationsPerTrack, onValueChange = { onObservationsChanged(it) }, valueRange = 1f..16f ) } HorizontalDivider(thickness = 0.5.dp) TextButton( modifier = Modifier.align(CenterHorizontally), onClick = onPurgeAllObservations ) { Text(text = "Purge All Observations") } } } }}
@Preview(showBackground = true)@Preview(uiMode = Configuration.UI_MODE_NIGHT_YES, showBackground = true)@Composablefun DynamicEntityLayerPropertiesPreview() { SampleAppTheme { DynamicEntityLayerProperties( isTrackLineVisible = true, isPrevObservationsVisible = true, observationsPerTrack = 5f ) }}/* 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. * */
package com.esri.arcgismaps.sample.adddynamicentitylayer.components
import android.app.Applicationimport androidx.compose.runtime.mutableFloatStateOfimport androidx.compose.runtime.mutableStateOfimport androidx.lifecycle.AndroidViewModelimport com.arcgismaps.mapping.ArcGISMapimport com.arcgismaps.mapping.BasemapStyleimport com.arcgismaps.mapping.Viewpointimport com.arcgismaps.mapping.layers.DynamicEntityLayerimport com.arcgismaps.realtime.ArcGISStreamServiceimport com.arcgismaps.realtime.ArcGISStreamServiceFilterimport com.esri.arcgismaps.sample.adddynamicentitylayer.Rimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.launch
class MapViewModel( application: Application, private val sampleCoroutineScope: CoroutineScope,) : AndroidViewModel(application) {
// set the state of the switches and slider val trackLineCheckedState = mutableStateOf(false) val prevObservationCheckedState = mutableStateOf(false) val trackSliderValue = mutableFloatStateOf(5f)
// flag to show or dismiss the bottom sheet val isBottomSheetVisible = mutableStateOf(false)
// create ArcGIS Stream Service private val streamService = ArcGISStreamService(application.getString(R.string.stream_service_url))
// create ArcGISStreamServiceFilter private val streamServiceFilter = ArcGISStreamServiceFilter()
// layer displaying the dynamic entities on the map private val dynamicEntityLayer: DynamicEntityLayer
// define ArcGIS map using Streets basemap val map = ArcGISMap(BasemapStyle.ArcGISStreets).apply { initialViewpoint = Viewpoint(40.559691, -111.869001, 150000.0) }
/** * set the data source for the dynamic entity layer. */ init { // set condition on the ArcGISStreamServiceFilter to limit the amount of data coming from the server streamServiceFilter.whereClause = "speed > 0" streamService.apply { filter = streamServiceFilter // sets the maximum time (in seconds) an observation remains in the application. purgeOptions.maximumDuration = 300.0 } dynamicEntityLayer = DynamicEntityLayer(streamService)
// add the dynamic entity layer to the map's operational layers map.operationalLayers.add(dynamicEntityLayer) }
// disconnects the stream service fun disconnectStreamService() { sampleCoroutineScope.launch { streamService.disconnect() } }
// connects the stream service fun connectStreamService() { sampleCoroutineScope.launch { streamService.connect() } }
// to dismiss the bottom sheet fun dismissBottomSheet() { isBottomSheetVisible.value = false }
// to manage bottomSheet visibility fun showBottomSheet() { isBottomSheetVisible.value = true }
// to manage track lines visibility fun trackLineVisibility(checkedValue: Boolean) { trackLineCheckedState.value = checkedValue dynamicEntityLayer.trackDisplayProperties.showTrackLine = trackLineCheckedState.value }
// to manage previous observations visibility fun prevObservationsVisibility(checkedValue: Boolean) { prevObservationCheckedState.value = checkedValue dynamicEntityLayer.trackDisplayProperties.showPreviousObservations = prevObservationCheckedState.value }
// to set the maximum number of observations displayed per track fun setObservations(sliderValue: Float) { trackSliderValue.floatValue = sliderValue dynamicEntityLayer.trackDisplayProperties.maximumObservations = trackSliderValue.floatValue.toInt() }
// remove all dynamic entity observations from the in-memory data cache as well as from the map fun purgeAllObservations() { sampleCoroutineScope.launch { streamService.purgeAll() } }}/* 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. * */
package com.esri.arcgismaps.sample.adddynamicentitylayer.screens
import android.app.Applicationimport androidx.compose.foundation.layout.Arrangementimport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.Rowimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.paddingimport androidx.compose.material3.Scaffoldimport androidx.compose.material3.Textimport androidx.compose.material3.TextButtonimport androidx.compose.runtime.Composableimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.rememberCoroutineScopeimport androidx.compose.runtime.setValueimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.platform.LocalContextimport androidx.compose.ui.unit.dpimport com.arcgismaps.toolkit.geoviewcompose.MapViewimport com.esri.arcgismaps.sample.adddynamicentitylayer.components.DynamicEntityLayerPropertiesimport com.esri.arcgismaps.sample.adddynamicentitylayer.components.MapViewModelimport com.esri.arcgismaps.sample.sampleslib.components.BottomSheetimport com.esri.arcgismaps.sample.sampleslib.components.SampleTopAppBar
/** * Main screen layout for the sample app */@Composablefun MainScreen(sampleName: String) { /// coroutineScope that will be cancelled when this call leaves the composition val sampleCoroutineScope = rememberCoroutineScope() // get the application context val application = LocalContext.current.applicationContext as Application
// create a ViewModel to handle MapView interactions val mapViewModel = remember { MapViewModel(application, sampleCoroutineScope) }
// display connect/disconnect based on the boolean state var isDisconnected by remember { mutableStateOf(false) }
Scaffold( topBar = { SampleTopAppBar(title = sampleName) }, content = { Column( modifier = Modifier .fillMaxSize() .padding(it) ) { // composable function that wraps the MapView MapView( modifier = Modifier .fillMaxSize() .weight(1f), arcGISMap = mapViewModel.map, onSingleTapConfirmed = { mapViewModel.dismissBottomSheet() }, onPan = { mapViewModel.dismissBottomSheet() } ) Row( modifier = Modifier .padding(12.dp) .fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween ) { TextButton(onClick = { if (!isDisconnected) mapViewModel.disconnectStreamService() else mapViewModel.connectStreamService() isDisconnected = !isDisconnected }) { Text(text = if (!isDisconnected) "Disconnect" else "Connect") } TextButton(onClick = { mapViewModel.showBottomSheet() }) { Text(text = "Dynamic Entity Settings") } }
} // display a bottom sheet to set dynamic entity layer properties BottomSheet(isVisible = mapViewModel.isBottomSheetVisible.value) { DynamicEntityLayerProperties( onTrackLineVisibilityChanged = mapViewModel::trackLineVisibility, onPrevObservationsVisibilityChanged = mapViewModel::prevObservationsVisibility, onObservationsChanged = mapViewModel::setObservations, onPurgeAllObservations = mapViewModel::purgeAllObservations, isTrackLineVisible = mapViewModel.trackLineCheckedState.value, isPrevObservationsVisible = mapViewModel.prevObservationCheckedState.value, observationsPerTrack = mapViewModel.trackSliderValue.floatValue, onDismiss = { mapViewModel.dismissBottomSheet() } ) } } )}