Skip to content

Add custom dynamic entity data source

View on GitHubSample viewer app

Create a custom dynamic entity data source and display it using a dynamic entity layer.

Image of add custom dynamic entity data source

Use case

Developers can create a custom DynamicEntityDataSource to be able to visualize data from a variety of different feeds as dynamic entities using a DynamicEntityLayer. An example of this is in a mobile situational awareness app, where a custom DynamicEntityDataSource can be used to connect to peer-to-peer feeds in order to visualize real-time location tracks from teammates in the field.

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

How it works

Configure the custom data source:

  1. Create a custom data source using a CustomDynamicEntityDataSource.EntityFeedProvider.
  2. Override feed with a SharedFlow<CustomDynamicEntityDataSource.FeedEvent>.
  3. Override onLoad() to specify the DynamicEntityDataSourceInfo for a given unique entity ID field and a list of Field objects matching the fields in the data source.
  4. Override OnConnect() to begin asynchronously processing observations from the custom data source.
  5. Loop through the observations and deserialize each observation into a Point object and a Map<String, Any?> containing the attributes.
  6. Emit an observation in the custom data source feed with CustomDynamicEntityDataSource.FeedEvent.NewObservation(point, attributes).

Configure the MapView:

  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. Use MapView.identify(...) to display a dynamic entity's attributes in a Callout.

Relevant API

  • CustomDynamicEntityDataSource.EntityFeedProvider
  • DynamicEntity
  • DynamicEntityDataSource
  • DynamicEntityLayer
  • LabelDefinition
  • TrackDisplayProperties

About the data

This sample uses a .json file containing observations of marine vessels in the Pacific North West hosted on ArcGIS Online.

Additional information

In this sample, we iterate through features in a GeoJSON file to mimic messages coming from a real-time feed. You can create a custom dynamic entity data source to process any data that contains observations which can be translated into map points (com.arcgismaps.geometry.Point objects) with associated Map<String, Any?> attributes.

This sample uses the GeoView-Compose Toolkit module to implement a composable MapView, which supports the use of Callouts.

Tags

callout, data, dynamic, entity, flow, geoview-compose, label, labeling, live, real-time, stream, track

Sample Code

MapViewModel.ktMapViewModel.ktDownloadActivity.ktMainActivity.ktCustomEntityFeedProvider.ktMainScreen.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 /* Copyright 2024 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.addcustomdynamicentitydatasource.components  import android.app.Application import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.ui.unit.dp import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import com.arcgismaps.arcgisservices.LabelingPlacement import com.arcgismaps.mapping.ArcGISMap import com.arcgismaps.mapping.BasemapStyle import com.arcgismaps.mapping.GeoElement 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.layers.Layer import com.arcgismaps.mapping.symbology.TextSymbol import com.arcgismaps.mapping.view.SingleTapConfirmedEvent import com.arcgismaps.realtime.ConnectionStatus import com.arcgismaps.realtime.CustomDynamicEntityDataSource import com.arcgismaps.realtime.DynamicEntityObservation import com.arcgismaps.toolkit.geoviewcompose.MapViewProxy import com.esri.arcgismaps.sample.addcustomdynamicentitydatasource.R import com.esri.arcgismaps.sample.sampleslib.components.MessageDialogViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.launch import java.io.File import kotlin.time.Duration.Companion.milliseconds  class MapViewModel(application: Application) : AndroidViewModel(application) {   // Keep track of connected status string state.  var connectionStatusString by mutableStateOf("")  private set   // Set connection status string in he UI.  private fun updateConnectionStatusString(connectionStatus: String) {  connectionStatusString = connectionStatus  }   private val provisionPath: String by lazy {  application.getExternalFilesDir(null)?.path.toString() + File.separator + application.getString(  R.string.add_custom_dynamic_entity_data_source_app_name  )  }   // Create a new custom feed provider that processes observations from a JSON file.  // 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.  private val feedProvider = CustomEntityFeedProvider(  fileName = "$provisionPath/AIS_MarineCadastre_SelectedVessels_CustomDataSource.jsonl",  entityIdField = "MMSI",  delayDuration = 10.milliseconds  )   private val dynamicEntityDataSource = CustomDynamicEntityDataSource(feedProvider).apply {  // Observe the connection status of the custom data source.  viewModelScope.launch {  connectionStatus.collect { connectionStatus ->  updateConnectionStatusString(  when (connectionStatus) {  is ConnectionStatus.Connected -> "Connected"  is ConnectionStatus.Disconnected -> "Disconnected"  is ConnectionStatus.Connecting -> "Connecting"  is ConnectionStatus.Failed -> "Failed"  }  )  }  }  }   // Create the dynamic entity layer using the custom data source.  private val dynamicEntityLayer = DynamicEntityLayer(dynamicEntityDataSource).apply {  trackDisplayProperties.apply {  // Set up the track display properties, these properties will be used to configure the appearance of the track line and previous observations.  showPreviousObservations = true  showTrackLine = true  maximumObservations = 20  }   // Define the label expression to be used, in this case we will use the "VesselName" for each of the dynamic entities.  val simpleLabelExpression = SimpleLabelExpression("[VesselName]")   // Set the text symbol color and size for the labels.  val labelSymbol = TextSymbol().apply {  color = com.arcgismaps.Color.red  size = 12.0F  }   // Add the label definition to the dynamic entity layer and enable labels.  labelDefinitions.add(LabelDefinition(simpleLabelExpression, labelSymbol).apply {  // Set the label position.  placement = LabelingPlacement.PointAboveCenter  })  labelsEnabled = true  }   val arcGISMap = ArcGISMap(BasemapStyle.ArcGISOceans).apply {  initialViewpoint = Viewpoint(47.984, -123.657, 3e6)  // Add the dynamic entity layer to the map.  operationalLayers.add(dynamicEntityLayer)  }   // Create a mapViewProxy that will be used to identify features in the MapView.  // This should also be passed to the composable MapView this mapViewProxy is associated with.  val mapViewProxy = MapViewProxy()   // create a ViewModel to handle dialog interactions  val messageDialogVM: MessageDialogViewModel = MessageDialogViewModel()   fun dynamicEntityDataSourceConnect() =  viewModelScope.launch { dynamicEntityDataSource.connect() }   fun dynamicEntityDataSourceDisconnect() =  viewModelScope.launch { dynamicEntityDataSource.disconnect() }   // Keep track of the currently selected GeoElement.  var selectedGeoElement by mutableStateOf<GeoElement?>(null)  private set   // Keep track of the most recent observation string.  var observationString by mutableStateOf("")  private set   // Keep track of the Coroutine Scope where observations on being collected on, so that it can  // be cancelled on subsequent identifies.  private var observationsJob: Job? = null   /**  * Identifies the tapped screen coordinate in the provided [singleTapConfirmedEvent]  */  fun identify(singleTapConfirmedEvent: SingleTapConfirmedEvent) {  viewModelScope.launch {  // If collecting observations on a previous identify, now cancel and stop collecting.  observationsJob?.cancelAndJoin()  // identify the cluster in the feature layer on the tapped coordinate  mapViewProxy.identify(  dynamicEntityLayer as Layer,  screenCoordinate = singleTapConfirmedEvent.screenCoordinate,  tolerance = 12.dp,  maximumResults = 1  ).onSuccess { result ->  (result.geoElements.firstOrNull() as? DynamicEntityObservation)?.let { observation ->  // Set the identified dynamic entity, used to display the callout.  selectedGeoElement = observation.dynamicEntity  // Define a new CoroutineScope to collect observation events on.  observationsJob = launch(Dispatchers.IO) {  // Collect observation events and update the observation string accordingly.  observation.dynamicEntity?.dynamicEntityChangedEvent?.collect { dynamicEntityChangedInfo ->  // Parse the observation attributes, filter out empty values, and remove  // starting and ending {}s.  observationString = dynamicEntityChangedInfo  .receivedObservation?.attributes?.filter {  it.value.toString().isNotEmpty() && !it.key.contains("globalid")  }.toString()  .replaceFirst("{", " ")  .removeSuffix("}")  .replace(",", "\n")  }  }  // If no observation is found, set the selectedGeoElement to null.  } ?: run {  selectedGeoElement = null  observationString = "Waiting for a new observation ..."  }  }.onFailure { error ->  messageDialogVM.showMessageDialog(  title = "Error identifying results: ${error.message.toString()}",  description = error.cause.toString()  )  }  }  } }

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