Show a callout with formatted content for a KML feature.

Use case
A user may wish to select a KML feature to view relevant information about it.
How to use the sample
Tap a feature to identify it. Feature information will be displayed in a callout.
Note: the KML layer used in this sample contains a screen overlay. The screen overlay contains a legend and the logos for NOAA and the NWS. You cannot identify the screen overlay.
How it works
- Use the
onSingleTapConfirmedmodifier onMapViewto get the screen point where a user tapped. - On tap:
- Call
MapViewProxy.identify(layer =.., screenCoordinate =.., tolerance =..)passing in theKMLLayer, screen point, and tolerance. - Await the result of the identify and then get the
KMLPlacemarkfrom the result. - Create a callout at the calculated map point and populate the callout content with text from the placemark’s
balloonContent. NOTE: KML supports defining HTML for balloon content and may need to be converted from HTML to text. - Show the callout.
Note: There are several types of KML features. This sample only identifies features of type KMLPlacemark.
Relevant API
- IdentifyLayerResult
- KMLLayer
- KMLPlacemark
- MapViewProxy
About the data
This sample shows a forecast for significant weather within the U.S. Regions of severe thunderstorms, flooding, snowfall, and freezing rain are shown.
Additional information
KML features can have rich HTML content, including images.
Tags
Keyhole, KML, KMZ, NOAA, NWS, OGC, weather
Sample code
/* 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.identifykmlfeatures.components
import android.app.Applicationimport androidx.compose.ui.unit.dpimport androidx.lifecycle.AndroidViewModelimport androidx.lifecycle.viewModelScopeimport com.arcgismaps.geometry.Pointimport com.arcgismaps.mapping.ArcGISMapimport com.arcgismaps.mapping.BasemapStyleimport com.arcgismaps.mapping.kml.KmlDatasetimport com.arcgismaps.mapping.kml.KmlPlacemarkimport com.arcgismaps.mapping.layers.KmlLayerimport com.arcgismaps.mapping.view.GraphicsOverlayimport com.arcgismaps.mapping.view.SingleTapConfirmedEventimport com.arcgismaps.toolkit.geoviewcompose.MapViewProxyimport com.esri.arcgismaps.sample.sampleslib.components.MessageDialogViewModelimport kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.coroutines.flow.StateFlowimport kotlinx.coroutines.flow.asStateFlowimport kotlinx.coroutines.launch
class IdentifyKMLFeaturesViewModel(app: Application) : AndroidViewModel(app) { val arcGISMap = ArcGISMap(BasemapStyle.ArcGISDarkGray)
val mapViewProxy = MapViewProxy()
// The KML dataset is created from a URL that points to a KML file containing weather forecast data. The KML layer is then created using this dataset. val kmlDataset = KmlDataset(uri = "https://www.arcgis.com/sharing/rest/content/items/f5e0e5cd088846a5b97b7ed66a8bad5c/data")
// The KML layer is created using the KML dataset. This layer will be added to the map's operational layers. val forecastLayer = KmlLayer(kmlDataset = kmlDataset)
// A MutableStateFlow to track the loading state of the KML layer. This can be used to show a loading indicator in the UI while the layer is being loaded. private val _isLoading = MutableStateFlow(false)
// A MutableStateFlow to track the currently selected point and its associated HTML content. private val _pointAndHtml = MutableStateFlow<Pair<Point, String>?>(null) val pointAndHtml: StateFlow<Pair<Point, String>?> = _pointAndHtml.asStateFlow()
// A MutableStateFlow to track the graphics overlay used for displaying the tap location. This can be used to show a marker at the location where the user tapped on the map. private val _tapLocationGraphicsOverlay = MutableStateFlow(GraphicsOverlay()) val tapLocationGraphicsOverlay: StateFlow<GraphicsOverlay> = _tapLocationGraphicsOverlay.asStateFlow()
// Create a message dialog view model for handling error messages val messageDialogVM = MessageDialogViewModel()
init { viewModelScope.launch { _isLoading.value = true arcGISMap.operationalLayers.apply { add(forecastLayer) } forecastLayer.load().onSuccess { arcGISMap.load().onFailure { messageDialogVM.showMessageDialog(it) } // If the layer has a full extent after loading, use MapViewProxy to set the viewpoint. forecastLayer.fullExtent?.let { extent -> mapViewProxy.setViewpointGeometry(boundingGeometry = extent, paddingInDips = 25.0) } }.onFailure { error -> messageDialogVM.showMessageDialog( title = "Failed to load KML layer", description = error.message.toString() ) } _isLoading.value = false } }
fun onSingleTapConfirmed(event: SingleTapConfirmedEvent) { viewModelScope.launch { val identifyLayerResult = mapViewProxy.identify(layer = forecastLayer, screenCoordinate = event.screenCoordinate, tolerance = 10.0.dp).getOrNull() // Check if the identified result is not null and has geoElements. if (identifyLayerResult != null && identifyLayerResult.geoElements.isNotEmpty()) { // Get the first KML placemark from the identify layer result's geoElements. val firstKMLPlacemark : KmlPlacemark? = identifyLayerResult.geoElements.filterIsInstance<KmlPlacemark>().firstOrNull() if(firstKMLPlacemark != null){ // Google Earth only displays the placemarks with description or extended data. // To match its behavior, add a description placeholder if it is empty. if(firstKMLPlacemark.description.isEmpty()){ firstKMLPlacemark.description = "Weather Condition" } val kmlText = firstKMLPlacemark.balloonContent //Update the state with the identified point and HTML content to be displayed in the callout. event.mapPoint?.let { mapPoint -> _pointAndHtml.value = Pair(mapPoint, kmlText) } }else{ _pointAndHtml.value = null } } else { _pointAndHtml.value = null } } }}/* 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.identifykmlfeatures
import android.os.Bundleimport androidx.activity.ComponentActivityimport androidx.activity.compose.setContentimport androidx.activity.enableEdgeToEdgeimport androidx.compose.material3.MaterialThemeimport androidx.compose.material3.Surfaceimport com.esri.arcgismaps.sample.sampleslib.theme.SampleAppThemeimport com.esri.arcgismaps.sample.identifykmlfeatures.screens.IdentifyKMLFeaturesScreen
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() setContent { SampleAppTheme { Surface(color = MaterialTheme.colorScheme.background) { IdentifyKMLFeaturesScreen() } } } }}/* 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.identifykmlfeatures.screens
import android.widget.TextViewimport androidx.compose.animation.AnimatedVisibilityimport androidx.compose.animation.core.MutableTransitionStateimport androidx.compose.animation.fadeInimport androidx.compose.animation.fadeOutimport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.layout.wrapContentSizeimport androidx.compose.material3.MaterialThemeimport androidx.compose.material3.Scaffoldimport androidx.compose.runtime.Composableimport androidx.compose.runtime.collectAsStateimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.saveable.rememberSaveableimport androidx.compose.runtime.setValueimport androidx.compose.ui.Modifierimport androidx.compose.ui.geometry.Offsetimport androidx.compose.ui.graphics.Colorimport androidx.compose.ui.node.Refimport androidx.compose.ui.res.stringResourceimport androidx.compose.ui.unit.dpimport androidx.compose.ui.viewinterop.AndroidViewimport androidx.core.text.HtmlCompatimport androidx.lifecycle.viewmodel.compose.viewModelimport com.arcgismaps.geometry.Pointimport com.arcgismaps.toolkit.geoviewcompose.GeoViewScopeimport com.arcgismaps.toolkit.geoviewcompose.LeaderPositionimport com.arcgismaps.toolkit.geoviewcompose.MapViewimport com.esri.arcgismaps.sample.identifykmlfeatures.Rimport com.esri.arcgismaps.sample.identifykmlfeatures.components.IdentifyKMLFeaturesViewModelimport com.esri.arcgismaps.sample.sampleslib.components.MessageDialogimport com.esri.arcgismaps.sample.sampleslib.components.SampleTopAppBar
/** * Main screen layout for the sample app */@Composablefun IdentifyKMLFeaturesScreen( mapViewModel: IdentifyKMLFeaturesViewModel = viewModel()) { val pointAndHtml = mapViewModel.pointAndHtml.collectAsState().value val point = pointAndHtml?.first val htmlText = pointAndHtml?.second val offset = Offset.Zero val tapLocationGraphicsOverlay = mapViewModel.tapLocationGraphicsOverlay.collectAsState().value var rotateOffsetWithGeoView by rememberSaveable { mutableStateOf(false) } var calloutVisibility by rememberSaveable { mutableStateOf(true) } // animate to a visible transition state val calloutVisibleState = remember { MutableTransitionState(false) }.apply { targetState = point != null && calloutVisibility }
Scaffold( topBar = { SampleTopAppBar(title = stringResource(R.string.identify_kml_features_app_name)) }, content = { Column( modifier = Modifier .fillMaxSize() .padding(it), ) { MapView( modifier = Modifier .fillMaxSize() .weight(1f), arcGISMap = mapViewModel.arcGISMap, mapViewProxy = mapViewModel.mapViewProxy, graphicsOverlays = listOf(tapLocationGraphicsOverlay), onSingleTapConfirmed = mapViewModel::onSingleTapConfirmed, content = { GeoViewScopeContent( mapPoint = point, htmlText = htmlText, calloutVisibleState = calloutVisibleState, rotateOffsetWithGeoView = rotateOffsetWithGeoView, offset = offset ) } ) }
mapViewModel.messageDialogVM.apply { if (dialogStatus) { MessageDialog( title = messageTitle, description = messageDescription, onDismissRequest = ::dismissDialog ) } } } )}
/** * Displays the callout at the tapped location on the map or scene. * * This function is responsible for managing callout at the coordinates of the [mapPoint]. * It uses animated visibility to show or hide the callout based on the state provided. */@Composablefun GeoViewScope.GeoViewScopeContent( mapPoint: Point?, htmlText: String?, calloutVisibleState: MutableTransitionState<Boolean>, rotateOffsetWithGeoView: Boolean, offset: Offset) { val lastMapPoint = remember { Ref<Point>() } lastMapPoint.value = mapPoint ?: lastMapPoint.value
AnimatedVisibility( calloutVisibleState, enter = fadeIn(), exit = fadeOut() ) { lastMapPoint.value?.let { Callout( modifier = Modifier.wrapContentSize(), location = it, leaderPosition = LeaderPosition.Automatic, rotateOffsetWithGeoView = rotateOffsetWithGeoView, offset = offset ) { Column(Modifier.padding(4.dp)) { HtmlText( html = htmlText ?: "", htmlFlag = HtmlCompat.FROM_HTML_MODE_COMPACT, textColor = MaterialTheme.colorScheme.onBackground, ) } } } }}
/** * AndroidView wrapper for the view-based [TextView] which is able to display a styled spannable [html]. * Currently, Compose does not provide a tool to buildAnnotatedString for HTML styled spannable text. */@Composablefun HtmlText(modifier: Modifier = Modifier, html: String, htmlFlag: Int, textColor: Color) { AndroidView( modifier = modifier, factory = { context -> TextView(context) }, update = { it.text = HtmlCompat.fromHtml(html, htmlFlag) it.setTextColor(textColor.hashCode()) } )}