Learn how to execute a SQL query to return features A feature is a single record, also known as a row, that represents a real-world entity. It typically contains a geometry (point, multipoint, polyline, or polygon) and attributes but it can also contain just attributes. Learn more from a feature layer A feature layer (server-side) is a spatially-enabled table in a feature service. All features in a feature layer share the same geometry type and set of fields. Learn more based on spatial and attribute Attributes are fields and values for a single feature or non-spatial record. They are typically stored in a database or service such as a feature service. Learn more criteria.

query a feature layer

A feature layer A feature layer (server-side) is a spatially-enabled table in a feature service. All features in a feature layer share the same geometry type and set of fields. Learn more can contain a large number of features A feature is a single record, also known as a row, that represents a real-world entity. It typically contains a geometry (point, multipoint, polyline, or polygon) and attributes but it can also contain just attributes. Learn more stored in ArcGIS. You can query a layer to access a subset of its features using any combination of spatial and attribute Attributes are fields and values for a single feature or non-spatial record. They are typically stored in a database or service such as a feature service. Learn more criteria. You can control whether or not each feature’s geometry A geometry is a geometric shape, such as a point, polyline, or polygon, that contains one or more coordinates and a spatial reference. Learn more is returned, as well as which attributes are included in the results. Queries allow you to return a well-defined subset of your hosted data for analysis or display in your app.

In this tutorial, you’ll write code to perform SQL queries that return a subset of features A feature is a single record, also known as a row, that represents a real-world entity. It typically contains a geometry (point, multipoint, polyline, or polygon) and attributes but it can also contain just attributes. Learn more in the LA County Parcel feature layer A feature layer (server-side) is a spatially-enabled table in a feature service. All features in a feature layer share the same geometry type and set of fields. Learn more (containing over 2.4 million features). Features that meet the query criteria are selected in the map.

Prerequisites

Before starting this tutorial, you need the following:

  1. An ArcGIS Location Platform or ArcGIS Online account.

  2. A development and deployment environment that meets the system requirements.

  3. An IDE for Android development in Kotlin.

Develop or Download

You have two options for completing this tutorial:

  1. Option 1: Develop the code or
  2. Option 2: Download the completed solution

Option 1: Develop the code

Open an Android Studio project

  1. Open the project you created by completing the Display a map tutorial.

  2. Continue with the following instructions to execute a SQL query to return features from a feature layer based on spatial and attribute criteria.

  3. Modify the old project for use in this new tutorial.

Add import statements

  1. Modify import statements to reference the packages and classes required for this tutorial.

    MainScreen.kt
    @file:OptIn(ExperimentalMaterial3Api::class)
    package com.example.app.screens
    import android.content.Context
    import android.widget.Toast
    import androidx.compose.foundation.layout.Column
    import androidx.compose.foundation.layout.fillMaxSize
    import androidx.compose.foundation.layout.fillMaxWidth
    import androidx.compose.foundation.layout.padding
    import androidx.compose.material3.DropdownMenuItem
    import androidx.compose.material3.ExperimentalMaterial3Api
    import androidx.compose.material3.ExposedDropdownMenuBox
    import androidx.compose.material3.MenuAnchorType
    import androidx.compose.material3.Scaffold
    import androidx.compose.material3.Text
    import androidx.compose.material3.TextField
    import androidx.compose.material3.TopAppBar
    import androidx.compose.runtime.Composable
    import androidx.compose.runtime.mutableStateOf
    import androidx.compose.runtime.remember
    import androidx.compose.runtime.rememberCoroutineScope
    import androidx.compose.ui.Modifier
    import androidx.compose.ui.platform.LocalContext
    import androidx.compose.ui.res.stringResource
    import com.arcgismaps.data.QueryParameters
    import com.arcgismaps.data.ServiceFeatureTable
    import com.arcgismaps.geometry.Envelope
    import com.arcgismaps.mapping.ArcGISMap
    import com.arcgismaps.mapping.BasemapStyle
    import com.arcgismaps.mapping.Viewpoint
    import com.arcgismaps.mapping.layers.FeatureLayer
    import com.arcgismaps.toolkit.geoviewcompose.MapView
    import com.example.app.R
    import kotlinx.coroutines.Job
  2. In the MainScreen composable, create variables that will be passed to various functions in the MainScreen.kt file.

    MainScreen.kt
    @Composable
    fun MainScreen() {
    val context = LocalContext.current
    val coroutineScope = rememberCoroutineScope()
    val currentQueryJob = remember { mutableStateOf<Job?>(null) }
    // Store the current viewpoint geometry extent of the map.
    val currentExtent = remember { mutableStateOf<Envelope?>(null) }
    Scaffold(
    topBar = { TopAppBar(title = { Text(text = stringResource(id = R.string.app_name)) }) }
    ) {
    MapView(
    modifier = Modifier.fillMaxSize(),
    arcGISMap = map,
    )
    }
    }

Create the Parcels feature layer and create a map with it

You will create a service feature table from a feature service URL. Then you will create a feature layer from that table and create an ArcGISMap with the feature layer.

  1. In the MainScreen block, create a ServiceFeatureTable using the feature service URL. Next, create a FeatureLayer using that service feature table. Define both serviceFeatureTable and featureLayer as local variables in the MainScreen composable.

    MainScreen.kt
    @Composable
    fun MainScreen() {
    val context = LocalContext.current
    val coroutineScope = rememberCoroutineScope()
    val currentQueryJob = remember { mutableStateOf<Job?>(null) }
    // Store the current viewpoint geometry extent of the map.
    val currentExtent = remember { mutableStateOf<Envelope?>(null) }
    // Create a service feature table from a Los Angeles County parcels feature service.
    val serviceFeatureTable = ServiceFeatureTable(
    uri = "https://services3.arcgis.com/GVgbJbqm8hXASVYi/arcgis/rest/services/LA_County_Parcels/FeatureServer/0"
    )
    val featureLayer = remember { FeatureLayer.createWithFeatureTable(serviceFeatureTable) }
    Scaffold(
    topBar = { TopAppBar(title = { Text(text = stringResource(id = R.string.app_name)) }) }
    ) {
    MapView(
    modifier = Modifier.fillMaxSize(),
    arcGISMap = map,
    )
    }
    }
  2. Modify the top-level function createMap() to take a FeatureLayer. Then add the feature layer to the operationalLayers property of MapView.

    MainScreen.kt
    66 collapsed lines
    @file:OptIn(ExperimentalMaterial3Api::class)
    package com.example.app.screens
    import android.content.Context
    import android.widget.Toast
    import androidx.compose.foundation.layout.Column
    import androidx.compose.foundation.layout.fillMaxSize
    import androidx.compose.foundation.layout.fillMaxWidth
    import androidx.compose.foundation.layout.padding
    import androidx.compose.material3.DropdownMenuItem
    import androidx.compose.material3.ExperimentalMaterial3Api
    import androidx.compose.material3.ExposedDropdownMenuBox
    import androidx.compose.material3.MenuAnchorType
    import androidx.compose.material3.Scaffold
    import androidx.compose.material3.Text
    import androidx.compose.material3.TextField
    import androidx.compose.material3.TopAppBar
    import androidx.compose.runtime.Composable
    import androidx.compose.runtime.mutableStateOf
    import androidx.compose.runtime.remember
    import androidx.compose.runtime.rememberCoroutineScope
    import androidx.compose.ui.Modifier
    import androidx.compose.ui.platform.LocalContext
    import androidx.compose.ui.res.stringResource
    import com.arcgismaps.data.QueryParameters
    import com.arcgismaps.data.ServiceFeatureTable
    import com.arcgismaps.geometry.Envelope
    import com.arcgismaps.mapping.ArcGISMap
    import com.arcgismaps.mapping.BasemapStyle
    import com.arcgismaps.mapping.Viewpoint
    import com.arcgismaps.mapping.layers.FeatureLayer
    import com.arcgismaps.toolkit.geoviewcompose.MapView
    import com.example.app.R
    import kotlinx.coroutines.Job
    import kotlinx.coroutines.launch
    @Composable
    fun MainScreen() {
    val context = LocalContext.current
    val coroutineScope = rememberCoroutineScope()
    val currentQueryJob = remember { mutableStateOf<Job?>(null) }
    // Store the current viewpoint geometry extent of the map.
    val currentExtent = remember { mutableStateOf<Envelope?>(null) }
    // Create a service feature table from a Los Angeles County parcels feature service.
    val serviceFeatureTable = ServiceFeatureTable(
    uri = "https://services3.arcgis.com/GVgbJbqm8hXASVYi/arcgis/rest/services/LA_County_Parcels/FeatureServer/0"
    )
    val featureLayer = remember { FeatureLayer.createWithFeatureTable(serviceFeatureTable) }
    Scaffold(
    topBar = { TopAppBar(title = { Text(text = stringResource(id = R.string.app_name)) }) }
    ) {
    MapView(
    modifier = Modifier.fillMaxSize(),
    arcGISMap = map,
    )
    }
    }
    fun createMap(featureLayer: FeatureLayer): ArcGISMap {
    return ArcGISMap(BasemapStyle.ArcGISTopographic).apply {
    initialViewpoint = Viewpoint(
    latitude = 34.0270,
    longitude = -118.8050,
    scale = 72000.0
    )
    operationalLayers.add(featureLayer)
    }
    }
    49 collapsed lines
    /**
    * Query the [serviceFeatureTable] based on the [whereExpression] on the given
    * [queryExtent] and select the resulting features on the [featureLayer]
    */
    suspend fun queryFeatureLayer(
    context: Context,
    serviceFeatureTable: ServiceFeatureTable,
    featureLayer: FeatureLayer,
    whereExpression: String,
    queryExtent: Envelope?
    ) {
    // Clear any previous selections.
    featureLayer.clearSelection()
    // Create query parameters with the where expression and the current extent
    // and have geometry values returned in the results.
    val queryParameters = QueryParameters().apply {
    whereClause = whereExpression
    returnGeometry = true
    geometry = queryExtent
    }
    try {
    // Query the feature table with the query parameters.
    val featureQueryResult = serviceFeatureTable.queryFeatures(queryParameters).getOrThrow()
    // Iterate through the result and select the features on the feature layer.
    val resultIterator = featureQueryResult.iterator()
    if (resultIterator.hasNext()) {
    resultIterator.forEach { feature ->
    featureLayer.selectFeature(feature)
    }
    } else {
    showMessage(
    context,
    "No parcels found in the current extent, using Where expression: $whereExpression"
    )
    }
    } catch (e: Exception) {
    showMessage(context, "Feature search failed for: $whereExpression, ${e.message}")
    }
    }
    fun showMessage(context: Context, message: String) {
    Toast.makeText(context, message, Toast.LENGTH_LONG).show()
    }
  3. In the MainScreen composable, modify the existing createMap() call by passing featureLayer as a parameter.

    MainScreen.kt
    37 collapsed lines
    @file:OptIn(ExperimentalMaterial3Api::class)
    package com.example.app.screens
    import android.content.Context
    import android.widget.Toast
    import androidx.compose.foundation.layout.Column
    import androidx.compose.foundation.layout.fillMaxSize
    import androidx.compose.foundation.layout.fillMaxWidth
    import androidx.compose.foundation.layout.padding
    import androidx.compose.material3.DropdownMenuItem
    import androidx.compose.material3.ExperimentalMaterial3Api
    import androidx.compose.material3.ExposedDropdownMenuBox
    import androidx.compose.material3.MenuAnchorType
    import androidx.compose.material3.Scaffold
    import androidx.compose.material3.Text
    import androidx.compose.material3.TextField
    import androidx.compose.material3.TopAppBar
    import androidx.compose.runtime.Composable
    import androidx.compose.runtime.mutableStateOf
    import androidx.compose.runtime.remember
    import androidx.compose.runtime.rememberCoroutineScope
    import androidx.compose.ui.Modifier
    import androidx.compose.ui.platform.LocalContext
    import androidx.compose.ui.res.stringResource
    import com.arcgismaps.data.QueryParameters
    import com.arcgismaps.data.ServiceFeatureTable
    import com.arcgismaps.geometry.Envelope
    import com.arcgismaps.mapping.ArcGISMap
    import com.arcgismaps.mapping.BasemapStyle
    import com.arcgismaps.mapping.Viewpoint
    import com.arcgismaps.mapping.layers.FeatureLayer
    import com.arcgismaps.toolkit.geoviewcompose.MapView
    import com.example.app.R
    import kotlinx.coroutines.Job
    import kotlinx.coroutines.launch
    @Composable
    fun MainScreen() {
    val context = LocalContext.current
    val coroutineScope = rememberCoroutineScope()
    val currentQueryJob = remember { mutableStateOf<Job?>(null) }
    // Store the current viewpoint geometry extent of the map.
    val currentExtent = remember { mutableStateOf<Envelope?>(null) }
    // Create a service feature table from a Los Angeles County parcels feature service.
    val serviceFeatureTable = ServiceFeatureTable(
    uri = "https://services3.arcgis.com/GVgbJbqm8hXASVYi/arcgis/rest/services/LA_County_Parcels/FeatureServer/0"
    )
    val featureLayer = remember { FeatureLayer.createWithFeatureTable(serviceFeatureTable) }
    val map = remember {
    createMap(featureLayer)
    }
    Scaffold(
    topBar = { TopAppBar(title = { Text(text = stringResource(id = R.string.app_name)) }) }
    ) {
    MapView(
    modifier = Modifier.fillMaxSize(),
    arcGISMap = map,
    )
    }
    }
    63 collapsed lines
    fun createMap(featureLayer: FeatureLayer): ArcGISMap {
    return ArcGISMap(BasemapStyle.ArcGISTopographic).apply {
    initialViewpoint = Viewpoint(
    latitude = 34.0270,
    longitude = -118.8050,
    scale = 72000.0
    )
    operationalLayers.add(featureLayer)
    }
    }
    /**
    * Query the [serviceFeatureTable] based on the [whereExpression] on the given
    * [queryExtent] and select the resulting features on the [featureLayer]
    */
    suspend fun queryFeatureLayer(
    context: Context,
    serviceFeatureTable: ServiceFeatureTable,
    featureLayer: FeatureLayer,
    whereExpression: String,
    queryExtent: Envelope?
    ) {
    // Clear any previous selections.
    featureLayer.clearSelection()
    // Create query parameters with the where expression and the current extent
    // and have geometry values returned in the results.
    val queryParameters = QueryParameters().apply {
    whereClause = whereExpression
    returnGeometry = true
    geometry = queryExtent
    }
    try {
    // Query the feature table with the query parameters.
    val featureQueryResult = serviceFeatureTable.queryFeatures(queryParameters).getOrThrow()
    // Iterate through the result and select the features on the feature layer.
    val resultIterator = featureQueryResult.iterator()
    if (resultIterator.hasNext()) {
    resultIterator.forEach { feature ->
    featureLayer.selectFeature(feature)
    }
    } else {
    showMessage(
    context,
    "No parcels found in the current extent, using Where expression: $whereExpression"
    )
    }
    } catch (e: Exception) {
    showMessage(context, "Feature search failed for: $whereExpression, ${e.message}")
    }
    }
    fun showMessage(context: Context, message: String) {
    Toast.makeText(context, message, Toast.LENGTH_LONG).show()
    }

Create a function to query the feature layer

Create a function that clears any currently selected features and executes a new query to find features in the map’s current extent that meet the selected attribute expression (the SQL WHERE expression). It then gets the features returned by FeatureQueryResult and selects them (in yellow highlight) in the parcels layer.

  1. Define a top-level suspend function named queryFeatureLayer(). Declare the parameters shown below.

    MainScreen.kt
    137 collapsed lines
    @file:OptIn(ExperimentalMaterial3Api::class)
    package com.example.app.screens
    import android.content.Context
    import android.widget.Toast
    import androidx.compose.foundation.layout.Column
    import androidx.compose.foundation.layout.fillMaxSize
    import androidx.compose.foundation.layout.fillMaxWidth
    import androidx.compose.foundation.layout.padding
    import androidx.compose.material3.DropdownMenuItem
    import androidx.compose.material3.ExperimentalMaterial3Api
    import androidx.compose.material3.ExposedDropdownMenuBox
    import androidx.compose.material3.MenuAnchorType
    import androidx.compose.material3.Scaffold
    import androidx.compose.material3.Text
    import androidx.compose.material3.TextField
    import androidx.compose.material3.TopAppBar
    import androidx.compose.runtime.Composable
    import androidx.compose.runtime.mutableStateOf
    import androidx.compose.runtime.remember
    import androidx.compose.runtime.rememberCoroutineScope
    import androidx.compose.ui.Modifier
    import androidx.compose.ui.platform.LocalContext
    import androidx.compose.ui.res.stringResource
    import com.arcgismaps.data.QueryParameters
    import com.arcgismaps.data.ServiceFeatureTable
    import com.arcgismaps.geometry.Envelope
    import com.arcgismaps.mapping.ArcGISMap
    import com.arcgismaps.mapping.BasemapStyle
    import com.arcgismaps.mapping.Viewpoint
    import com.arcgismaps.mapping.layers.FeatureLayer
    import com.arcgismaps.toolkit.geoviewcompose.MapView
    import com.example.app.R
    import kotlinx.coroutines.Job
    import kotlinx.coroutines.launch
    @Composable
    fun MainScreen() {
    val context = LocalContext.current
    val coroutineScope = rememberCoroutineScope()
    val currentQueryJob = remember { mutableStateOf<Job?>(null) }
    // Store the current viewpoint geometry extent of the map.
    val currentExtent = remember { mutableStateOf<Envelope?>(null) }
    // Create a service feature table from a Los Angeles County parcels feature service.
    val serviceFeatureTable = ServiceFeatureTable(
    uri = "https://services3.arcgis.com/GVgbJbqm8hXASVYi/arcgis/rest/services/LA_County_Parcels/FeatureServer/0"
    )
    val featureLayer = remember { FeatureLayer.createWithFeatureTable(serviceFeatureTable) }
    val map = remember {
    createMap(featureLayer)
    }
    Scaffold(
    topBar = { TopAppBar(title = { Text(text = stringResource(id = R.string.app_name)) }) }
    ) {
    MapView(
    modifier = Modifier.fillMaxSize(),
    arcGISMap = map,
    )
    }
    }
    @Composable
    fun QueryDropDownMenu(onItemClicked: (String) -> Unit) {
    val expanded = remember { mutableStateOf(false) }
    var selectedText = remember { mutableStateOf("") }
    val options = listOf(
    "UseType = \'Government\'",
    "UseType = \'Residential\'",
    "UseType = \'Irrigated Farm\'",
    "TaxRateArea = 10853",
    "TaxRateArea = 10860",
    "Roll_LandValue > 1000000",
    "Roll_LandValue < 1000000"
    )
    ExposedDropdownMenuBox(
    expanded = expanded.value,
    onExpandedChange = {
    expanded.value = !expanded.value
    }
    ) {
    TextField(
    modifier = Modifier.menuAnchor(type = MenuAnchorType.PrimaryNotEditable, enabled = true),
    value = selectedText.value,
    onValueChange = {},
    readOnly = true,
    label = { Text("Select a query expression") }
    )
    ExposedDropdownMenu(
    expanded = expanded.value,
    onDismissRequest = {
    expanded.value = false
    }
    ) {
    options.forEach { selectionOption ->
    DropdownMenuItem(
    text = { Text(text = selectionOption) },
    onClick = {
    selectedText.value = selectionOption
    expanded.value = false
    onItemClicked(selectedText.value)
    }
    )
    }
    }
    }
    }
    fun createMap(featureLayer: FeatureLayer): ArcGISMap {
    return ArcGISMap(BasemapStyle.ArcGISTopographic).apply {
    initialViewpoint = Viewpoint(
    latitude = 34.0270,
    longitude = -118.8050,
    scale = 72000.0
    )
    operationalLayers.add(featureLayer)
    }
    }
    /**
    * Query the [serviceFeatureTable] based on the [whereExpression] on the given
    * [queryExtent] and select the resulting features on the [featureLayer]
    */
    suspend fun queryFeatureLayer(
    context: Context,
    serviceFeatureTable: ServiceFeatureTable,
    featureLayer: FeatureLayer,
    whereExpression: String,
    queryExtent: Envelope?
    ) {
    }
    4 collapsed lines
    fun showMessage(context: Context, message: String) {
    Toast.makeText(context, message, Toast.LENGTH_LONG).show()
    }
  2. Create a QueryParameters instance, and set the whereClause, returnGeometry, and geometry properties on the query parameters.

    MainScreen.kt
    137 collapsed lines
    @file:OptIn(ExperimentalMaterial3Api::class)
    package com.example.app.screens
    import android.content.Context
    import android.widget.Toast
    import androidx.compose.foundation.layout.Column
    import androidx.compose.foundation.layout.fillMaxSize
    import androidx.compose.foundation.layout.fillMaxWidth
    import androidx.compose.foundation.layout.padding
    import androidx.compose.material3.DropdownMenuItem
    import androidx.compose.material3.ExperimentalMaterial3Api
    import androidx.compose.material3.ExposedDropdownMenuBox
    import androidx.compose.material3.MenuAnchorType
    import androidx.compose.material3.Scaffold
    import androidx.compose.material3.Text
    import androidx.compose.material3.TextField
    import androidx.compose.material3.TopAppBar
    import androidx.compose.runtime.Composable
    import androidx.compose.runtime.mutableStateOf
    import androidx.compose.runtime.remember
    import androidx.compose.runtime.rememberCoroutineScope
    import androidx.compose.ui.Modifier
    import androidx.compose.ui.platform.LocalContext
    import androidx.compose.ui.res.stringResource
    import com.arcgismaps.data.QueryParameters
    import com.arcgismaps.data.ServiceFeatureTable
    import com.arcgismaps.geometry.Envelope
    import com.arcgismaps.mapping.ArcGISMap
    import com.arcgismaps.mapping.BasemapStyle
    import com.arcgismaps.mapping.Viewpoint
    import com.arcgismaps.mapping.layers.FeatureLayer
    import com.arcgismaps.toolkit.geoviewcompose.MapView
    import com.example.app.R
    import kotlinx.coroutines.Job
    import kotlinx.coroutines.launch
    @Composable
    fun MainScreen() {
    val context = LocalContext.current
    val coroutineScope = rememberCoroutineScope()
    val currentQueryJob = remember { mutableStateOf<Job?>(null) }
    // Store the current viewpoint geometry extent of the map.
    val currentExtent = remember { mutableStateOf<Envelope?>(null) }
    // Create a service feature table from a Los Angeles County parcels feature service.
    val serviceFeatureTable = ServiceFeatureTable(
    uri = "https://services3.arcgis.com/GVgbJbqm8hXASVYi/arcgis/rest/services/LA_County_Parcels/FeatureServer/0"
    )
    val featureLayer = remember { FeatureLayer.createWithFeatureTable(serviceFeatureTable) }
    val map = remember {
    createMap(featureLayer)
    }
    Scaffold(
    topBar = { TopAppBar(title = { Text(text = stringResource(id = R.string.app_name)) }) }
    ) {
    MapView(
    modifier = Modifier.fillMaxSize(),
    arcGISMap = map,
    )
    }
    }
    @Composable
    fun QueryDropDownMenu(onItemClicked: (String) -> Unit) {
    val expanded = remember { mutableStateOf(false) }
    var selectedText = remember { mutableStateOf("") }
    val options = listOf(
    "UseType = \'Government\'",
    "UseType = \'Residential\'",
    "UseType = \'Irrigated Farm\'",
    "TaxRateArea = 10853",
    "TaxRateArea = 10860",
    "Roll_LandValue > 1000000",
    "Roll_LandValue < 1000000"
    )
    ExposedDropdownMenuBox(
    expanded = expanded.value,
    onExpandedChange = {
    expanded.value = !expanded.value
    }
    ) {
    TextField(
    modifier = Modifier.menuAnchor(type = MenuAnchorType.PrimaryNotEditable, enabled = true),
    value = selectedText.value,
    onValueChange = {},
    readOnly = true,
    label = { Text("Select a query expression") }
    )
    ExposedDropdownMenu(
    expanded = expanded.value,
    onDismissRequest = {
    expanded.value = false
    }
    ) {
    options.forEach { selectionOption ->
    DropdownMenuItem(
    text = { Text(text = selectionOption) },
    onClick = {
    selectedText.value = selectionOption
    expanded.value = false
    onItemClicked(selectedText.value)
    }
    )
    }
    }
    }
    }
    fun createMap(featureLayer: FeatureLayer): ArcGISMap {
    return ArcGISMap(BasemapStyle.ArcGISTopographic).apply {
    initialViewpoint = Viewpoint(
    latitude = 34.0270,
    longitude = -118.8050,
    scale = 72000.0
    )
    operationalLayers.add(featureLayer)
    }
    }
    /**
    * Query the [serviceFeatureTable] based on the [whereExpression] on the given
    * [queryExtent] and select the resulting features on the [featureLayer]
    */
    suspend fun queryFeatureLayer(
    context: Context,
    serviceFeatureTable: ServiceFeatureTable,
    featureLayer: FeatureLayer,
    whereExpression: String,
    queryExtent: Envelope?
    ) {
    // Clear any previous selections.
    featureLayer.clearSelection()
    // Create query parameters with the where expression and the current extent
    // and have geometry values returned in the results.
    val queryParameters = QueryParameters().apply {
    whereClause = whereExpression
    returnGeometry = true
    geometry = queryExtent
    }
    }
    4 collapsed lines
    fun showMessage(context: Context, message: String) {
    Toast.makeText(context, message, Toast.LENGTH_LONG).show()
    }
  3. Within try-catch statements, call ServiceFeatureTable.queryFeatures(), passing queryParameters.

    Next, get the iterator on featureQueryResult. If the resultIterator has any features to return, then iterate over those features and select them (with highlight) on the feature layer.

    Then show a message if the query returns no features in the current extent. Last, display a message in the catch clause in case the feature search failed.

    MainScreen.kt
    156 collapsed lines
    @file:OptIn(ExperimentalMaterial3Api::class)
    package com.example.app.screens
    import android.content.Context
    import android.widget.Toast
    import androidx.compose.foundation.layout.Column
    import androidx.compose.foundation.layout.fillMaxSize
    import androidx.compose.foundation.layout.fillMaxWidth
    import androidx.compose.foundation.layout.padding
    import androidx.compose.material3.DropdownMenuItem
    import androidx.compose.material3.ExperimentalMaterial3Api
    import androidx.compose.material3.ExposedDropdownMenuBox
    import androidx.compose.material3.MenuAnchorType
    import androidx.compose.material3.Scaffold
    import androidx.compose.material3.Text
    import androidx.compose.material3.TextField
    import androidx.compose.material3.TopAppBar
    import androidx.compose.runtime.Composable
    import androidx.compose.runtime.mutableStateOf
    import androidx.compose.runtime.remember
    import androidx.compose.runtime.rememberCoroutineScope
    import androidx.compose.ui.Modifier
    import androidx.compose.ui.platform.LocalContext
    import androidx.compose.ui.res.stringResource
    import com.arcgismaps.data.QueryParameters
    import com.arcgismaps.data.ServiceFeatureTable
    import com.arcgismaps.geometry.Envelope
    import com.arcgismaps.mapping.ArcGISMap
    import com.arcgismaps.mapping.BasemapStyle
    import com.arcgismaps.mapping.Viewpoint
    import com.arcgismaps.mapping.layers.FeatureLayer
    import com.arcgismaps.toolkit.geoviewcompose.MapView
    import com.example.app.R
    import kotlinx.coroutines.Job
    import kotlinx.coroutines.launch
    @Composable
    fun MainScreen() {
    val context = LocalContext.current
    val coroutineScope = rememberCoroutineScope()
    val currentQueryJob = remember { mutableStateOf<Job?>(null) }
    // Store the current viewpoint geometry extent of the map.
    val currentExtent = remember { mutableStateOf<Envelope?>(null) }
    // Create a service feature table from a Los Angeles County parcels feature service.
    val serviceFeatureTable = ServiceFeatureTable(
    uri = "https://services3.arcgis.com/GVgbJbqm8hXASVYi/arcgis/rest/services/LA_County_Parcels/FeatureServer/0"
    )
    val featureLayer = remember { FeatureLayer.createWithFeatureTable(serviceFeatureTable) }
    val map = remember {
    createMap(featureLayer)
    }
    Scaffold(
    topBar = { TopAppBar(title = { Text(text = stringResource(id = R.string.app_name)) }) }
    ) {
    Column(
    Modifier.fillMaxSize().padding(it)
    ) {
    QueryDropDownMenu(
    onItemClicked = { sqlQueryExpression ->
    // Cancel the previous query job if it exists.
    currentQueryJob.value?.cancel()
    currentQueryJob.value = coroutineScope.launch {
    queryFeatureLayer(
    context = context,
    serviceFeatureTable = serviceFeatureTable,
    featureLayer = featureLayer,
    whereExpression = sqlQueryExpression,
    queryExtent = currentExtent.value
    )
    }
    })
    MapView(
    modifier = Modifier.fillMaxSize(),
    arcGISMap = map,
    )
    }
    }
    @Composable
    fun QueryDropDownMenu(onItemClicked: (String) -> Unit) {
    val expanded = remember { mutableStateOf(false) }
    var selectedText = remember { mutableStateOf("") }
    val options = listOf(
    "UseType = \'Government\'",
    "UseType = \'Residential\'",
    "UseType = \'Irrigated Farm\'",
    "TaxRateArea = 10853",
    "TaxRateArea = 10860",
    "Roll_LandValue > 1000000",
    "Roll_LandValue < 1000000"
    )
    ExposedDropdownMenuBox(
    expanded = expanded.value,
    onExpandedChange = {
    expanded.value = !expanded.value
    }
    ) {
    TextField(
    modifier = Modifier.menuAnchor(type = MenuAnchorType.PrimaryNotEditable, enabled = true),
    value = selectedText.value,
    onValueChange = {},
    readOnly = true,
    label = { Text("Select a query expression") }
    )
    ExposedDropdownMenu(
    expanded = expanded.value,
    onDismissRequest = {
    expanded.value = false
    }
    ) {
    options.forEach { selectionOption ->
    DropdownMenuItem(
    text = { Text(text = selectionOption) },
    onClick = {
    selectedText.value = selectionOption
    expanded.value = false
    onItemClicked(selectedText.value)
    }
    )
    }
    }
    }
    }
    fun createMap(featureLayer: FeatureLayer): ArcGISMap {
    return ArcGISMap(BasemapStyle.ArcGISTopographic).apply {
    initialViewpoint = Viewpoint(
    latitude = 34.0270,
    longitude = -118.8050,
    scale = 72000.0
    )
    operationalLayers.add(featureLayer)
    }
    }
    /**
    * Query the [serviceFeatureTable] based on the [whereExpression] on the given
    * [queryExtent] and select the resulting features on the [featureLayer]
    */
    suspend fun queryFeatureLayer(
    context: Context,
    serviceFeatureTable: ServiceFeatureTable,
    featureLayer: FeatureLayer,
    whereExpression: String,
    queryExtent: Envelope?
    ) {
    // Clear any previous selections.
    featureLayer.clearSelection()
    // Create query parameters with the where expression and the current extent
    // and have geometry values returned in the results.
    val queryParameters = QueryParameters().apply {
    whereClause = whereExpression
    returnGeometry = true
    geometry = queryExtent
    }
    try {
    // Query the feature table with the query parameters.
    val featureQueryResult = serviceFeatureTable.queryFeatures(queryParameters).getOrThrow()
    // Iterate through the result and select the features on the feature layer.
    val resultIterator = featureQueryResult.iterator()
    if (resultIterator.hasNext()) {
    resultIterator.forEach { feature ->
    featureLayer.selectFeature(feature)
    }
    } else {
    showMessage(
    context,
    "No parcels found in the current extent, using Where expression: $whereExpression"
    )
    }
    } catch (e: Exception) {
    showMessage(context, "Feature search failed for: $whereExpression, ${e.message}")
    }
    }
    4 collapsed lines
    fun showMessage(context: Context, message: String) {
    Toast.makeText(context, message, Toast.LENGTH_LONG).show()
    }

Create a drop-down menu for query expressions

Create a drop-down menu that allows the user to choose from a list of pre-defined SQL query expressions.

  1. Define a composable function named QueryDropDownMenu. Declare an onItemClicked parameter that takes a lambda to be invoked when the user selects an item from the drop-down menu.

    In the QueryDropDownMenu block, create two remember variables named expanded and selection.

    • The expanded variable holds a state value, of type MutableState<Boolean>, that indicates whether the drop-down menu is visually expanded on the device screen.

    • The selection variable holds a state value, of type MutableState<String>, indicates the item that the user chose from the drop-down menu.

    Create a list of the SQL query expressions and assign it to a variable named sqlQueryExpressions. Each expression is a string.

    MainScreen.kt
    72 collapsed lines
    @file:OptIn(ExperimentalMaterial3Api::class)
    package com.example.app.screens
    import android.content.Context
    import android.widget.Toast
    import androidx.compose.foundation.layout.Column
    import androidx.compose.foundation.layout.fillMaxSize
    import androidx.compose.foundation.layout.fillMaxWidth
    import androidx.compose.foundation.layout.padding
    import androidx.compose.material3.DropdownMenuItem
    import androidx.compose.material3.ExperimentalMaterial3Api
    import androidx.compose.material3.ExposedDropdownMenuBox
    import androidx.compose.material3.MenuAnchorType
    import androidx.compose.material3.Scaffold
    import androidx.compose.material3.Text
    import androidx.compose.material3.TextField
    import androidx.compose.material3.TopAppBar
    import androidx.compose.runtime.Composable
    import androidx.compose.runtime.mutableStateOf
    import androidx.compose.runtime.remember
    import androidx.compose.runtime.rememberCoroutineScope
    import androidx.compose.ui.Modifier
    import androidx.compose.ui.platform.LocalContext
    import androidx.compose.ui.res.stringResource
    import com.arcgismaps.data.QueryParameters
    import com.arcgismaps.data.ServiceFeatureTable
    import com.arcgismaps.geometry.Envelope
    import com.arcgismaps.mapping.ArcGISMap
    import com.arcgismaps.mapping.BasemapStyle
    import com.arcgismaps.mapping.Viewpoint
    import com.arcgismaps.mapping.layers.FeatureLayer
    import com.arcgismaps.toolkit.geoviewcompose.MapView
    import com.example.app.R
    import kotlinx.coroutines.Job
    import kotlinx.coroutines.launch
    @Composable
    fun MainScreen() {
    val context = LocalContext.current
    val coroutineScope = rememberCoroutineScope()
    val currentQueryJob = remember { mutableStateOf<Job?>(null) }
    // Store the current viewpoint geometry extent of the map.
    val currentExtent = remember { mutableStateOf<Envelope?>(null) }
    // Create a service feature table from a Los Angeles County parcels feature service.
    val serviceFeatureTable = ServiceFeatureTable(
    uri = "https://services3.arcgis.com/GVgbJbqm8hXASVYi/arcgis/rest/services/LA_County_Parcels/FeatureServer/0"
    )
    val featureLayer = remember { FeatureLayer.createWithFeatureTable(serviceFeatureTable) }
    val map = remember {
    createMap(featureLayer)
    }
    Scaffold(
    topBar = { TopAppBar(title = { Text(text = stringResource(id = R.string.app_name)) }) }
    ) {
    MapView(
    modifier = Modifier.fillMaxSize(),
    arcGISMap = map,
    )
    }
    }
    @Composable
    fun QueryDropDownMenu(onItemClicked: (String) -> Unit) {
    val expanded = remember { mutableStateOf(false) }
    var selectedText = remember { mutableStateOf("") }
    val options = listOf(
    "UseType = \'Government\'",
    "UseType = \'Residential\'",
    "UseType = \'Irrigated Farm\'",
    "TaxRateArea = 10853",
    "TaxRateArea = 10860",
    "Roll_LandValue > 1000000",
    "Roll_LandValue < 1000000"
    )
    }
    63 collapsed lines
    fun createMap(featureLayer: FeatureLayer): ArcGISMap {
    return ArcGISMap(BasemapStyle.ArcGISTopographic).apply {
    initialViewpoint = Viewpoint(
    latitude = 34.0270,
    longitude = -118.8050,
    scale = 72000.0
    )
    operationalLayers.add(featureLayer)
    }
    }
    /**
    * Query the [serviceFeatureTable] based on the [whereExpression] on the given
    * [queryExtent] and select the resulting features on the [featureLayer]
    */
    suspend fun queryFeatureLayer(
    context: Context,
    serviceFeatureTable: ServiceFeatureTable,
    featureLayer: FeatureLayer,
    whereExpression: String,
    queryExtent: Envelope?
    ) {
    // Clear any previous selections.
    featureLayer.clearSelection()
    // Create query parameters with the where expression and the current extent
    // and have geometry values returned in the results.
    val queryParameters = QueryParameters().apply {
    whereClause = whereExpression
    returnGeometry = true
    geometry = queryExtent
    }
    try {
    // Query the feature table with the query parameters.
    val featureQueryResult = serviceFeatureTable.queryFeatures(queryParameters).getOrThrow()
    // Iterate through the result and select the features on the feature layer.
    val resultIterator = featureQueryResult.iterator()
    if (resultIterator.hasNext()) {
    resultIterator.forEach { feature ->
    featureLayer.selectFeature(feature)
    }
    } else {
    showMessage(
    context,
    "No parcels found in the current extent, using Where expression: $whereExpression"
    )
    }
    } catch (e: Exception) {
    showMessage(context, "Feature search failed for: $whereExpression, ${e.message}")
    }
    }
    fun showMessage(context: Context, message: String) {
    Toast.makeText(context, message, Toast.LENGTH_LONG).show()
    }
  2. Call the ExposedDropDownMenuBox composable. Pass the following parameters:

    • The state value of the expanded variable.
    • A lambda that toggles the state value of the expanded variable. The lambda is automatically called when the exposed dropdown menu is clicked and the expansion state changes.

    In the ExposedDropDownMenuBox block, call the composable TextField. Pass the parameters shown below. For the value parameter, pass the state value of the selection variable.

    MainScreen.kt
    97 collapsed lines
    @file:OptIn(ExperimentalMaterial3Api::class)
    package com.example.app.screens
    import android.content.Context
    import android.widget.Toast
    import androidx.compose.foundation.layout.Column
    import androidx.compose.foundation.layout.fillMaxSize
    import androidx.compose.foundation.layout.fillMaxWidth
    import androidx.compose.foundation.layout.padding
    import androidx.compose.material3.DropdownMenuItem
    import androidx.compose.material3.ExperimentalMaterial3Api
    import androidx.compose.material3.ExposedDropdownMenuBox
    import androidx.compose.material3.MenuAnchorType
    import androidx.compose.material3.Scaffold
    import androidx.compose.material3.Text
    import androidx.compose.material3.TextField
    import androidx.compose.material3.TopAppBar
    import androidx.compose.runtime.Composable
    import androidx.compose.runtime.mutableStateOf
    import androidx.compose.runtime.remember
    import androidx.compose.runtime.rememberCoroutineScope
    import androidx.compose.ui.Modifier
    import androidx.compose.ui.platform.LocalContext
    import androidx.compose.ui.res.stringResource
    import com.arcgismaps.data.QueryParameters
    import com.arcgismaps.data.ServiceFeatureTable
    import com.arcgismaps.geometry.Envelope
    import com.arcgismaps.mapping.ArcGISMap
    import com.arcgismaps.mapping.BasemapStyle
    import com.arcgismaps.mapping.Viewpoint
    import com.arcgismaps.mapping.layers.FeatureLayer
    import com.arcgismaps.toolkit.geoviewcompose.MapView
    import com.example.app.R
    import kotlinx.coroutines.Job
    import kotlinx.coroutines.launch
    @Composable
    fun MainScreen() {
    val context = LocalContext.current
    val coroutineScope = rememberCoroutineScope()
    val currentQueryJob = remember { mutableStateOf<Job?>(null) }
    // Store the current viewpoint geometry extent of the map.
    val currentExtent = remember { mutableStateOf<Envelope?>(null) }
    // Create a service feature table from a Los Angeles County parcels feature service.
    val serviceFeatureTable = ServiceFeatureTable(
    uri = "https://services3.arcgis.com/GVgbJbqm8hXASVYi/arcgis/rest/services/LA_County_Parcels/FeatureServer/0"
    )
    val featureLayer = remember { FeatureLayer.createWithFeatureTable(serviceFeatureTable) }
    val map = remember {
    createMap(featureLayer)
    }
    Scaffold(
    topBar = { TopAppBar(title = { Text(text = stringResource(id = R.string.app_name)) }) }
    ) {
    Column(
    Modifier.fillMaxSize().padding(it)
    ) {
    QueryDropDownMenu(
    onItemClicked = { sqlQueryExpression ->
    // Cancel the previous query job if it exists.
    currentQueryJob.value?.cancel()
    currentQueryJob.value = coroutineScope.launch {
    queryFeatureLayer(
    context = context,
    serviceFeatureTable = serviceFeatureTable,
    featureLayer = featureLayer,
    whereExpression = sqlQueryExpression,
    queryExtent = currentExtent.value
    )
    }
    })
    MapView(
    modifier = Modifier.fillMaxSize(),
    arcGISMap = map,
    onViewpointChangedForBoundingGeometry = { viewpoint ->
    currentExtent.value = viewpoint.targetGeometry.extent
    }
    )
    }
    }
    }
    @Composable
    fun QueryDropDownMenu(onItemClicked: (String) -> Unit) {
    val expanded = remember { mutableStateOf(false) }
    var selectedText = remember { mutableStateOf("") }
    val options = listOf(
    "UseType = \'Government\'",
    "UseType = \'Residential\'",
    "UseType = \'Irrigated Farm\'",
    "TaxRateArea = 10853",
    "TaxRateArea = 10860",
    "Roll_LandValue > 1000000",
    "Roll_LandValue < 1000000"
    )
    ExposedDropdownMenuBox(
    expanded = expanded.value,
    onExpandedChange = {
    expanded.value = !expanded.value
    }
    ) {
    TextField(
    modifier = Modifier.menuAnchor(type = MenuAnchorType.PrimaryNotEditable, enabled = true),
    value = selectedText.value,
    onValueChange = {},
    readOnly = true,
    label = { Text("Select a query expression") }
    )
    }
    }
    63 collapsed lines
    fun createMap(featureLayer: FeatureLayer): ArcGISMap {
    return ArcGISMap(BasemapStyle.ArcGISTopographic).apply {
    initialViewpoint = Viewpoint(
    latitude = 34.0270,
    longitude = -118.8050,
    scale = 72000.0
    )
    operationalLayers.add(featureLayer)
    }
    }
    /**
    * Query the [serviceFeatureTable] based on the [whereExpression] on the given
    * [queryExtent] and select the resulting features on the [featureLayer]
    */
    suspend fun queryFeatureLayer(
    context: Context,
    serviceFeatureTable: ServiceFeatureTable,
    featureLayer: FeatureLayer,
    whereExpression: String,
    queryExtent: Envelope?
    ) {
    // Clear any previous selections.
    featureLayer.clearSelection()
    // Create query parameters with the where expression and the current extent
    // and have geometry values returned in the results.
    val queryParameters = QueryParameters().apply {
    whereClause = whereExpression
    returnGeometry = true
    geometry = queryExtent
    }
    try {
    // Query the feature table with the query parameters.
    val featureQueryResult = serviceFeatureTable.queryFeatures(queryParameters).getOrThrow()
    // Iterate through the result and select the features on the feature layer.
    val resultIterator = featureQueryResult.iterator()
    if (resultIterator.hasNext()) {
    resultIterator.forEach { feature ->
    featureLayer.selectFeature(feature)
    }
    } else {
    showMessage(
    context,
    "No parcels found in the current extent, using Where expression: $whereExpression"
    )
    }
    } catch (e: Exception) {
    showMessage(context, "Feature search failed for: $whereExpression, ${e.message}")
    }
    }
    fun showMessage(context: Context, message: String) {
    Toast.makeText(context, message, Toast.LENGTH_LONG).show()
    }
  3. Continuing in the ExposedDropDownMenuBox composable: call ExposedDropdownMenu. Pass the state value of the expanded variable. Also pass a lambda that sets the state value of expanded to false (that is, hides the displayed drop-down menu).

    In the ExposedDropDownMenu block, loop over the list of SQL query expressions. For each expression, call the DropDownMenuItem composable. Pass values for the following parameters.

    • For text, pass a lambda that adds a Text displaying the current SQL query expression.

    • For onClick, pass a lambda that does the following:

      • Assigns the selectionOption to the state value of the selection variable.
      • Sets the state value of the expanded variable to false (to hide the exposed drop-down menu when the user selects an item from the menu).
      • Call the onItemClicked parameter (the function passed to the QueryDropDownMenu) and pass the state value of the selection variable.
    MainScreen.kt
    97 collapsed lines
    @file:OptIn(ExperimentalMaterial3Api::class)
    package com.example.app.screens
    import android.content.Context
    import android.widget.Toast
    import androidx.compose.foundation.layout.Column
    import androidx.compose.foundation.layout.fillMaxSize
    import androidx.compose.foundation.layout.fillMaxWidth
    import androidx.compose.foundation.layout.padding
    import androidx.compose.material3.DropdownMenuItem
    import androidx.compose.material3.ExperimentalMaterial3Api
    import androidx.compose.material3.ExposedDropdownMenuBox
    import androidx.compose.material3.MenuAnchorType
    import androidx.compose.material3.Scaffold
    import androidx.compose.material3.Text
    import androidx.compose.material3.TextField
    import androidx.compose.material3.TopAppBar
    import androidx.compose.runtime.Composable
    import androidx.compose.runtime.mutableStateOf
    import androidx.compose.runtime.remember
    import androidx.compose.runtime.rememberCoroutineScope
    import androidx.compose.ui.Modifier
    import androidx.compose.ui.platform.LocalContext
    import androidx.compose.ui.res.stringResource
    import com.arcgismaps.data.QueryParameters
    import com.arcgismaps.data.ServiceFeatureTable
    import com.arcgismaps.geometry.Envelope
    import com.arcgismaps.mapping.ArcGISMap
    import com.arcgismaps.mapping.BasemapStyle
    import com.arcgismaps.mapping.Viewpoint
    import com.arcgismaps.mapping.layers.FeatureLayer
    import com.arcgismaps.toolkit.geoviewcompose.MapView
    import com.example.app.R
    import kotlinx.coroutines.Job
    import kotlinx.coroutines.launch
    @Composable
    fun MainScreen() {
    val context = LocalContext.current
    val coroutineScope = rememberCoroutineScope()
    val currentQueryJob = remember { mutableStateOf<Job?>(null) }
    // Store the current viewpoint geometry extent of the map.
    val currentExtent = remember { mutableStateOf<Envelope?>(null) }
    // Create a service feature table from a Los Angeles County parcels feature service.
    val serviceFeatureTable = ServiceFeatureTable(
    uri = "https://services3.arcgis.com/GVgbJbqm8hXASVYi/arcgis/rest/services/LA_County_Parcels/FeatureServer/0"
    )
    val featureLayer = remember { FeatureLayer.createWithFeatureTable(serviceFeatureTable) }
    val map = remember {
    createMap(featureLayer)
    }
    Scaffold(
    topBar = { TopAppBar(title = { Text(text = stringResource(id = R.string.app_name)) }) }
    ) {
    Column(
    Modifier.fillMaxSize().padding(it)
    ) {
    QueryDropDownMenu(
    onItemClicked = { sqlQueryExpression ->
    // Cancel the previous query job if it exists.
    currentQueryJob.value?.cancel()
    currentQueryJob.value = coroutineScope.launch {
    queryFeatureLayer(
    context = context,
    serviceFeatureTable = serviceFeatureTable,
    featureLayer = featureLayer,
    whereExpression = sqlQueryExpression,
    queryExtent = currentExtent.value
    )
    }
    })
    MapView(
    modifier = Modifier.fillMaxSize(),
    arcGISMap = map,
    onViewpointChangedForBoundingGeometry = { viewpoint ->
    currentExtent.value = viewpoint.targetGeometry.extent
    }
    )
    }
    }
    }
    @Composable
    fun QueryDropDownMenu(onItemClicked: (String) -> Unit) {
    val expanded = remember { mutableStateOf(false) }
    var selectedText = remember { mutableStateOf("") }
    val options = listOf(
    "UseType = \'Government\'",
    "UseType = \'Residential\'",
    "UseType = \'Irrigated Farm\'",
    "TaxRateArea = 10853",
    "TaxRateArea = 10860",
    "Roll_LandValue > 1000000",
    "Roll_LandValue < 1000000"
    )
    ExposedDropdownMenuBox(
    expanded = expanded.value,
    onExpandedChange = {
    expanded.value = !expanded.value
    }
    ) {
    TextField(
    modifier = Modifier.menuAnchor(type = MenuAnchorType.PrimaryNotEditable, enabled = true),
    value = selectedText.value,
    onValueChange = {},
    readOnly = true,
    label = { Text("Select a query expression") }
    )
    ExposedDropdownMenu(
    expanded = expanded.value,
    onDismissRequest = {
    expanded.value = false
    }
    ) {
    options.forEach { selectionOption ->
    DropdownMenuItem(
    text = { Text(text = selectionOption) },
    onClick = {
    selectedText.value = selectionOption
    expanded.value = false
    onItemClicked(selectedText.value)
    }
    )
    }
    }
    }
    }
    63 collapsed lines
    fun createMap(featureLayer: FeatureLayer): ArcGISMap {
    return ArcGISMap(BasemapStyle.ArcGISTopographic).apply {
    initialViewpoint = Viewpoint(
    latitude = 34.0270,
    longitude = -118.8050,
    scale = 72000.0
    )
    operationalLayers.add(featureLayer)
    }
    }
    /**
    * Query the [serviceFeatureTable] based on the [whereExpression] on the given
    * [queryExtent] and select the resulting features on the [featureLayer]
    */
    suspend fun queryFeatureLayer(
    context: Context,
    serviceFeatureTable: ServiceFeatureTable,
    featureLayer: FeatureLayer,
    whereExpression: String,
    queryExtent: Envelope?
    ) {
    // Clear any previous selections.
    featureLayer.clearSelection()
    // Create query parameters with the where expression and the current extent
    // and have geometry values returned in the results.
    val queryParameters = QueryParameters().apply {
    whereClause = whereExpression
    returnGeometry = true
    geometry = queryExtent
    }
    try {
    // Query the feature table with the query parameters.
    val featureQueryResult = serviceFeatureTable.queryFeatures(queryParameters).getOrThrow()
    // Iterate through the result and select the features on the feature layer.
    val resultIterator = featureQueryResult.iterator()
    if (resultIterator.hasNext()) {
    resultIterator.forEach { feature ->
    featureLayer.selectFeature(feature)
    }
    } else {
    showMessage(
    context,
    "No parcels found in the current extent, using Where expression: $whereExpression"
    )
    }
    } catch (e: Exception) {
    showMessage(context, "Feature search failed for: $whereExpression, ${e.message}")
    }
    }
    fun showMessage(context: Context, message: String) {
    Toast.makeText(context, message, Toast.LENGTH_LONG).show()
    }

In Scaffold, call the QueryDropDownMenu composable.

  1. Inside the Scaffold block, find the MapView from the Display a map tutorial and replace it with a call of Column. A Column allows you to display the drop-down menu at the top of the screen and the map view directly below.

    MainScreen.kt
    58 collapsed lines
    @file:OptIn(ExperimentalMaterial3Api::class)
    package com.example.app.screens
    import android.content.Context
    import android.widget.Toast
    import androidx.compose.foundation.layout.Column
    import androidx.compose.foundation.layout.fillMaxSize
    import androidx.compose.foundation.layout.fillMaxWidth
    import androidx.compose.foundation.layout.padding
    import androidx.compose.material3.DropdownMenuItem
    import androidx.compose.material3.ExperimentalMaterial3Api
    import androidx.compose.material3.ExposedDropdownMenuBox
    import androidx.compose.material3.MenuAnchorType
    import androidx.compose.material3.Scaffold
    import androidx.compose.material3.Text
    import androidx.compose.material3.TextField
    import androidx.compose.material3.TopAppBar
    import androidx.compose.runtime.Composable
    import androidx.compose.runtime.mutableStateOf
    import androidx.compose.runtime.remember
    import androidx.compose.runtime.rememberCoroutineScope
    import androidx.compose.ui.Modifier
    import androidx.compose.ui.platform.LocalContext
    import androidx.compose.ui.res.stringResource
    import com.arcgismaps.data.QueryParameters
    import com.arcgismaps.data.ServiceFeatureTable
    import com.arcgismaps.geometry.Envelope
    import com.arcgismaps.mapping.ArcGISMap
    import com.arcgismaps.mapping.BasemapStyle
    import com.arcgismaps.mapping.Viewpoint
    import com.arcgismaps.mapping.layers.FeatureLayer
    import com.arcgismaps.toolkit.geoviewcompose.MapView
    import com.example.app.R
    import kotlinx.coroutines.Job
    import kotlinx.coroutines.launch
    @Composable
    fun MainScreen() {
    val context = LocalContext.current
    val coroutineScope = rememberCoroutineScope()
    val currentQueryJob = remember { mutableStateOf<Job?>(null) }
    // Store the current viewpoint geometry extent of the map.
    val currentExtent = remember { mutableStateOf<Envelope?>(null) }
    // Create a service feature table from a Los Angeles County parcels feature service.
    val serviceFeatureTable = ServiceFeatureTable(
    uri = "https://services3.arcgis.com/GVgbJbqm8hXASVYi/arcgis/rest/services/LA_County_Parcels/FeatureServer/0"
    )
    val featureLayer = remember { FeatureLayer.createWithFeatureTable(serviceFeatureTable) }
    val map = remember {
    createMap(featureLayer)
    }
    Scaffold(
    topBar = { TopAppBar(title = { Text(text = stringResource(id = R.string.app_name)) }) }
    ) {
    Column(
    Modifier.fillMaxSize().padding(it)
    ) {
    }
    }
    116 collapsed lines
    }
    @Composable
    fun QueryDropDownMenu(onItemClicked: (String) -> Unit) {
    val expanded = remember { mutableStateOf(false) }
    var selectedText = remember { mutableStateOf("") }
    val options = listOf(
    "UseType = \'Government\'",
    "UseType = \'Residential\'",
    "UseType = \'Irrigated Farm\'",
    "TaxRateArea = 10853",
    "TaxRateArea = 10860",
    "Roll_LandValue > 1000000",
    "Roll_LandValue < 1000000"
    )
    ExposedDropdownMenuBox(
    expanded = expanded.value,
    onExpandedChange = {
    expanded.value = !expanded.value
    }
    ) {
    TextField(
    modifier = Modifier.menuAnchor(type = MenuAnchorType.PrimaryNotEditable, enabled = true),
    value = selectedText.value,
    onValueChange = {},
    readOnly = true,
    label = { Text("Select a query expression") }
    )
    ExposedDropdownMenu(
    expanded = expanded.value,
    onDismissRequest = {
    expanded.value = false
    }
    ) {
    options.forEach { selectionOption ->
    DropdownMenuItem(
    text = { Text(text = selectionOption) },
    onClick = {
    selectedText.value = selectionOption
    expanded.value = false
    onItemClicked(selectedText.value)
    }
    )
    }
    }
    }
    }
    fun createMap(featureLayer: FeatureLayer): ArcGISMap {
    return ArcGISMap(BasemapStyle.ArcGISTopographic).apply {
    initialViewpoint = Viewpoint(
    latitude = 34.0270,
    longitude = -118.8050,
    scale = 72000.0
    )
    operationalLayers.add(featureLayer)
    }
    }
    /**
    * Query the [serviceFeatureTable] based on the [whereExpression] on the given
    * [queryExtent] and select the resulting features on the [featureLayer]
    */
    suspend fun queryFeatureLayer(
    context: Context,
    serviceFeatureTable: ServiceFeatureTable,
    featureLayer: FeatureLayer,
    whereExpression: String,
    queryExtent: Envelope?
    ) {
    // Clear any previous selections.
    featureLayer.clearSelection()
    // Create query parameters with the where expression and the current extent
    // and have geometry values returned in the results.
    val queryParameters = QueryParameters().apply {
    whereClause = whereExpression
    returnGeometry = true
    geometry = queryExtent
    }
    try {
    // Query the feature table with the query parameters.
    val featureQueryResult = serviceFeatureTable.queryFeatures(queryParameters).getOrThrow()
    // Iterate through the result and select the features on the feature layer.
    val resultIterator = featureQueryResult.iterator()
    if (resultIterator.hasNext()) {
    resultIterator.forEach { feature ->
    featureLayer.selectFeature(feature)
    }
    } else {
    showMessage(
    context,
    "No parcels found in the current extent, using Where expression: $whereExpression"
    )
    }
    } catch (e: Exception) {
    showMessage(context, "Feature search failed for: $whereExpression, ${e.message}")
    }
    }
    fun showMessage(context: Context, message: String) {
    Toast.makeText(context, message, Toast.LENGTH_LONG).show()
    }
  2. Call the QueryDropDownMenu composable function you created above. For the onItemClicked parameter, pass a lambda that does the following:

    • Cancels any coroutine Job that is currently running.
    • Launches a coroutine.
    • Within the launch block, calls the queryFeatureLayer() function you defined above. You should pass the arguments shown below. Note that the sqlQueryExpression is the parameter passed to the lambda.
    MainScreen.kt
    58 collapsed lines
    @file:OptIn(ExperimentalMaterial3Api::class)
    package com.example.app.screens
    import android.content.Context
    import android.widget.Toast
    import androidx.compose.foundation.layout.Column
    import androidx.compose.foundation.layout.fillMaxSize
    import androidx.compose.foundation.layout.fillMaxWidth
    import androidx.compose.foundation.layout.padding
    import androidx.compose.material3.DropdownMenuItem
    import androidx.compose.material3.ExperimentalMaterial3Api
    import androidx.compose.material3.ExposedDropdownMenuBox
    import androidx.compose.material3.MenuAnchorType
    import androidx.compose.material3.Scaffold
    import androidx.compose.material3.Text
    import androidx.compose.material3.TextField
    import androidx.compose.material3.TopAppBar
    import androidx.compose.runtime.Composable
    import androidx.compose.runtime.mutableStateOf
    import androidx.compose.runtime.remember
    import androidx.compose.runtime.rememberCoroutineScope
    import androidx.compose.ui.Modifier
    import androidx.compose.ui.platform.LocalContext
    import androidx.compose.ui.res.stringResource
    import com.arcgismaps.data.QueryParameters
    import com.arcgismaps.data.ServiceFeatureTable
    import com.arcgismaps.geometry.Envelope
    import com.arcgismaps.mapping.ArcGISMap
    import com.arcgismaps.mapping.BasemapStyle
    import com.arcgismaps.mapping.Viewpoint
    import com.arcgismaps.mapping.layers.FeatureLayer
    import com.arcgismaps.toolkit.geoviewcompose.MapView
    import com.example.app.R
    import kotlinx.coroutines.Job
    import kotlinx.coroutines.launch
    @Composable
    fun MainScreen() {
    val context = LocalContext.current
    val coroutineScope = rememberCoroutineScope()
    val currentQueryJob = remember { mutableStateOf<Job?>(null) }
    // Store the current viewpoint geometry extent of the map.
    val currentExtent = remember { mutableStateOf<Envelope?>(null) }
    // Create a service feature table from a Los Angeles County parcels feature service.
    val serviceFeatureTable = ServiceFeatureTable(
    uri = "https://services3.arcgis.com/GVgbJbqm8hXASVYi/arcgis/rest/services/LA_County_Parcels/FeatureServer/0"
    )
    val featureLayer = remember { FeatureLayer.createWithFeatureTable(serviceFeatureTable) }
    val map = remember {
    createMap(featureLayer)
    }
    Scaffold(
    topBar = { TopAppBar(title = { Text(text = stringResource(id = R.string.app_name)) }) }
    ) {
    Column(
    Modifier.fillMaxSize().padding(it)
    ) {
    QueryDropDownMenu(
    onItemClicked = { sqlQueryExpression ->
    // Cancel the previous query job if it exists.
    currentQueryJob.value?.cancel()
    currentQueryJob.value = coroutineScope.launch {
    queryFeatureLayer(
    context = context,
    serviceFeatureTable = serviceFeatureTable,
    featureLayer = featureLayer,
    whereExpression = sqlQueryExpression,
    queryExtent = currentExtent.value
    )
    }
    })
    }
    }
    116 collapsed lines
    }
    @Composable
    fun QueryDropDownMenu(onItemClicked: (String) -> Unit) {
    val expanded = remember { mutableStateOf(false) }
    var selectedText = remember { mutableStateOf("") }
    val options = listOf(
    "UseType = \'Government\'",
    "UseType = \'Residential\'",
    "UseType = \'Irrigated Farm\'",
    "TaxRateArea = 10853",
    "TaxRateArea = 10860",
    "Roll_LandValue > 1000000",
    "Roll_LandValue < 1000000"
    )
    ExposedDropdownMenuBox(
    expanded = expanded.value,
    onExpandedChange = {
    expanded.value = !expanded.value
    }
    ) {
    TextField(
    modifier = Modifier.menuAnchor(type = MenuAnchorType.PrimaryNotEditable, enabled = true),
    value = selectedText.value,
    onValueChange = {},
    readOnly = true,
    label = { Text("Select a query expression") }
    )
    ExposedDropdownMenu(
    expanded = expanded.value,
    onDismissRequest = {
    expanded.value = false
    }
    ) {
    options.forEach { selectionOption ->
    DropdownMenuItem(
    text = { Text(text = selectionOption) },
    onClick = {
    selectedText.value = selectionOption
    expanded.value = false
    onItemClicked(selectedText.value)
    }
    )
    }
    }
    }
    }
    fun createMap(featureLayer: FeatureLayer): ArcGISMap {
    return ArcGISMap(BasemapStyle.ArcGISTopographic).apply {
    initialViewpoint = Viewpoint(
    latitude = 34.0270,
    longitude = -118.8050,
    scale = 72000.0
    )
    operationalLayers.add(featureLayer)
    }
    }
    /**
    * Query the [serviceFeatureTable] based on the [whereExpression] on the given
    * [queryExtent] and select the resulting features on the [featureLayer]
    */
    suspend fun queryFeatureLayer(
    context: Context,
    serviceFeatureTable: ServiceFeatureTable,
    featureLayer: FeatureLayer,
    whereExpression: String,
    queryExtent: Envelope?
    ) {
    // Clear any previous selections.
    featureLayer.clearSelection()
    // Create query parameters with the where expression and the current extent
    // and have geometry values returned in the results.
    val queryParameters = QueryParameters().apply {
    whereClause = whereExpression
    returnGeometry = true
    geometry = queryExtent
    }
    try {
    // Query the feature table with the query parameters.
    val featureQueryResult = serviceFeatureTable.queryFeatures(queryParameters).getOrThrow()
    // Iterate through the result and select the features on the feature layer.
    val resultIterator = featureQueryResult.iterator()
    if (resultIterator.hasNext()) {
    resultIterator.forEach { feature ->
    featureLayer.selectFeature(feature)
    }
    } else {
    showMessage(
    context,
    "No parcels found in the current extent, using Where expression: $whereExpression"
    )
    }
    } catch (e: Exception) {
    showMessage(context, "Feature search failed for: $whereExpression, ${e.message}")
    }
    }
    fun showMessage(context: Context, message: String) {
    Toast.makeText(context, message, Toast.LENGTH_LONG).show()
    }
  3. Add back the MapView.

    MainScreen.kt
    58 collapsed lines
    @file:OptIn(ExperimentalMaterial3Api::class)
    package com.example.app.screens
    import android.content.Context
    import android.widget.Toast
    import androidx.compose.foundation.layout.Column
    import androidx.compose.foundation.layout.fillMaxSize
    import androidx.compose.foundation.layout.fillMaxWidth
    import androidx.compose.foundation.layout.padding
    import androidx.compose.material3.DropdownMenuItem
    import androidx.compose.material3.ExperimentalMaterial3Api
    import androidx.compose.material3.ExposedDropdownMenuBox
    import androidx.compose.material3.MenuAnchorType
    import androidx.compose.material3.Scaffold
    import androidx.compose.material3.Text
    import androidx.compose.material3.TextField
    import androidx.compose.material3.TopAppBar
    import androidx.compose.runtime.Composable
    import androidx.compose.runtime.mutableStateOf
    import androidx.compose.runtime.remember
    import androidx.compose.runtime.rememberCoroutineScope
    import androidx.compose.ui.Modifier
    import androidx.compose.ui.platform.LocalContext
    import androidx.compose.ui.res.stringResource
    import com.arcgismaps.data.QueryParameters
    import com.arcgismaps.data.ServiceFeatureTable
    import com.arcgismaps.geometry.Envelope
    import com.arcgismaps.mapping.ArcGISMap
    import com.arcgismaps.mapping.BasemapStyle
    import com.arcgismaps.mapping.Viewpoint
    import com.arcgismaps.mapping.layers.FeatureLayer
    import com.arcgismaps.toolkit.geoviewcompose.MapView
    import com.example.app.R
    import kotlinx.coroutines.Job
    import kotlinx.coroutines.launch
    @Composable
    fun MainScreen() {
    val context = LocalContext.current
    val coroutineScope = rememberCoroutineScope()
    val currentQueryJob = remember { mutableStateOf<Job?>(null) }
    // Store the current viewpoint geometry extent of the map.
    val currentExtent = remember { mutableStateOf<Envelope?>(null) }
    // Create a service feature table from a Los Angeles County parcels feature service.
    val serviceFeatureTable = ServiceFeatureTable(
    uri = "https://services3.arcgis.com/GVgbJbqm8hXASVYi/arcgis/rest/services/LA_County_Parcels/FeatureServer/0"
    )
    val featureLayer = remember { FeatureLayer.createWithFeatureTable(serviceFeatureTable) }
    val map = remember {
    createMap(featureLayer)
    }
    Scaffold(
    topBar = { TopAppBar(title = { Text(text = stringResource(id = R.string.app_name)) }) }
    ) {
    Column(
    Modifier.fillMaxSize().padding(it)
    ) {
    QueryDropDownMenu(
    onItemClicked = { sqlQueryExpression ->
    // Cancel the previous query job if it exists.
    currentQueryJob.value?.cancel()
    currentQueryJob.value = coroutineScope.launch {
    queryFeatureLayer(
    context = context,
    serviceFeatureTable = serviceFeatureTable,
    featureLayer = featureLayer,
    whereExpression = sqlQueryExpression,
    queryExtent = currentExtent.value
    )
    }
    })
    MapView(
    modifier = Modifier.fillMaxSize(),
    arcGISMap = map,
    )
    }
    }
    116 collapsed lines
    }
    @Composable
    fun QueryDropDownMenu(onItemClicked: (String) -> Unit) {
    val expanded = remember { mutableStateOf(false) }
    var selectedText = remember { mutableStateOf("") }
    val options = listOf(
    "UseType = \'Government\'",
    "UseType = \'Residential\'",
    "UseType = \'Irrigated Farm\'",
    "TaxRateArea = 10853",
    "TaxRateArea = 10860",
    "Roll_LandValue > 1000000",
    "Roll_LandValue < 1000000"
    )
    ExposedDropdownMenuBox(
    expanded = expanded.value,
    onExpandedChange = {
    expanded.value = !expanded.value
    }
    ) {
    TextField(
    modifier = Modifier.menuAnchor(type = MenuAnchorType.PrimaryNotEditable, enabled = true),
    value = selectedText.value,
    onValueChange = {},
    readOnly = true,
    label = { Text("Select a query expression") }
    )
    ExposedDropdownMenu(
    expanded = expanded.value,
    onDismissRequest = {
    expanded.value = false
    }
    ) {
    options.forEach { selectionOption ->
    DropdownMenuItem(
    text = { Text(text = selectionOption) },
    onClick = {
    selectedText.value = selectionOption
    expanded.value = false
    onItemClicked(selectedText.value)
    }
    )
    }
    }
    }
    }
    fun createMap(featureLayer: FeatureLayer): ArcGISMap {
    return ArcGISMap(BasemapStyle.ArcGISTopographic).apply {
    initialViewpoint = Viewpoint(
    latitude = 34.0270,
    longitude = -118.8050,
    scale = 72000.0
    )
    operationalLayers.add(featureLayer)
    }
    }
    /**
    * Query the [serviceFeatureTable] based on the [whereExpression] on the given
    * [queryExtent] and select the resulting features on the [featureLayer]
    */
    suspend fun queryFeatureLayer(
    context: Context,
    serviceFeatureTable: ServiceFeatureTable,
    featureLayer: FeatureLayer,
    whereExpression: String,
    queryExtent: Envelope?
    ) {
    // Clear any previous selections.
    featureLayer.clearSelection()
    // Create query parameters with the where expression and the current extent
    // and have geometry values returned in the results.
    val queryParameters = QueryParameters().apply {
    whereClause = whereExpression
    returnGeometry = true
    geometry = queryExtent
    }
    try {
    // Query the feature table with the query parameters.
    val featureQueryResult = serviceFeatureTable.queryFeatures(queryParameters).getOrThrow()
    // Iterate through the result and select the features on the feature layer.
    val resultIterator = featureQueryResult.iterator()
    if (resultIterator.hasNext()) {
    resultIterator.forEach { feature ->
    featureLayer.selectFeature(feature)
    }
    } else {
    showMessage(
    context,
    "No parcels found in the current extent, using Where expression: $whereExpression"
    )
    }
    } catch (e: Exception) {
    showMessage(context, "Feature search failed for: $whereExpression, ${e.message}")
    }
    }
    fun showMessage(context: Context, message: String) {
    Toast.makeText(context, message, Toast.LENGTH_LONG).show()
    }
  4. Pass the onViewpointChangedForBoundingGeometry parameter to MapView. For that parameter, pass a lambda that assigns the current viewpoint’s extent to the state value of the currentExtent variable.

    MainScreen.kt
    58 collapsed lines
    @file:OptIn(ExperimentalMaterial3Api::class)
    package com.example.app.screens
    import android.content.Context
    import android.widget.Toast
    import androidx.compose.foundation.layout.Column
    import androidx.compose.foundation.layout.fillMaxSize
    import androidx.compose.foundation.layout.fillMaxWidth
    import androidx.compose.foundation.layout.padding
    import androidx.compose.material3.DropdownMenuItem
    import androidx.compose.material3.ExperimentalMaterial3Api
    import androidx.compose.material3.ExposedDropdownMenuBox
    import androidx.compose.material3.MenuAnchorType
    import androidx.compose.material3.Scaffold
    import androidx.compose.material3.Text
    import androidx.compose.material3.TextField
    import androidx.compose.material3.TopAppBar
    import androidx.compose.runtime.Composable
    import androidx.compose.runtime.mutableStateOf
    import androidx.compose.runtime.remember
    import androidx.compose.runtime.rememberCoroutineScope
    import androidx.compose.ui.Modifier
    import androidx.compose.ui.platform.LocalContext
    import androidx.compose.ui.res.stringResource
    import com.arcgismaps.data.QueryParameters
    import com.arcgismaps.data.ServiceFeatureTable
    import com.arcgismaps.geometry.Envelope
    import com.arcgismaps.mapping.ArcGISMap
    import com.arcgismaps.mapping.BasemapStyle
    import com.arcgismaps.mapping.Viewpoint
    import com.arcgismaps.mapping.layers.FeatureLayer
    import com.arcgismaps.toolkit.geoviewcompose.MapView
    import com.example.app.R
    import kotlinx.coroutines.Job
    import kotlinx.coroutines.launch
    @Composable
    fun MainScreen() {
    val context = LocalContext.current
    val coroutineScope = rememberCoroutineScope()
    val currentQueryJob = remember { mutableStateOf<Job?>(null) }
    // Store the current viewpoint geometry extent of the map.
    val currentExtent = remember { mutableStateOf<Envelope?>(null) }
    // Create a service feature table from a Los Angeles County parcels feature service.
    val serviceFeatureTable = ServiceFeatureTable(
    uri = "https://services3.arcgis.com/GVgbJbqm8hXASVYi/arcgis/rest/services/LA_County_Parcels/FeatureServer/0"
    )
    val featureLayer = remember { FeatureLayer.createWithFeatureTable(serviceFeatureTable) }
    val map = remember {
    createMap(featureLayer)
    }
    Scaffold(
    topBar = { TopAppBar(title = { Text(text = stringResource(id = R.string.app_name)) }) }
    ) {
    Column(
    Modifier.fillMaxSize().padding(it)
    ) {
    QueryDropDownMenu(
    onItemClicked = { sqlQueryExpression ->
    // Cancel the previous query job if it exists.
    currentQueryJob.value?.cancel()
    currentQueryJob.value = coroutineScope.launch {
    queryFeatureLayer(
    context = context,
    serviceFeatureTable = serviceFeatureTable,
    featureLayer = featureLayer,
    whereExpression = sqlQueryExpression,
    queryExtent = currentExtent.value
    )
    }
    })
    MapView(
    modifier = Modifier.fillMaxSize(),
    arcGISMap = map,
    onViewpointChangedForBoundingGeometry = { viewpoint ->
    currentExtent.value = viewpoint.targetGeometry.extent
    }
    )
    }
    }
    116 collapsed lines
    }
    @Composable
    fun QueryDropDownMenu(onItemClicked: (String) -> Unit) {
    val expanded = remember { mutableStateOf(false) }
    var selectedText = remember { mutableStateOf("") }
    val options = listOf(
    "UseType = \'Government\'",
    "UseType = \'Residential\'",
    "UseType = \'Irrigated Farm\'",
    "TaxRateArea = 10853",
    "TaxRateArea = 10860",
    "Roll_LandValue > 1000000",
    "Roll_LandValue < 1000000"
    )
    ExposedDropdownMenuBox(
    expanded = expanded.value,
    onExpandedChange = {
    expanded.value = !expanded.value
    }
    ) {
    TextField(
    modifier = Modifier.menuAnchor(type = MenuAnchorType.PrimaryNotEditable, enabled = true),
    value = selectedText.value,
    onValueChange = {},
    readOnly = true,
    label = { Text("Select a query expression") }
    )
    ExposedDropdownMenu(
    expanded = expanded.value,
    onDismissRequest = {
    expanded.value = false
    }
    ) {
    options.forEach { selectionOption ->
    DropdownMenuItem(
    text = { Text(text = selectionOption) },
    onClick = {
    selectedText.value = selectionOption
    expanded.value = false
    onItemClicked(selectedText.value)
    }
    )
    }
    }
    }
    }
    fun createMap(featureLayer: FeatureLayer): ArcGISMap {
    return ArcGISMap(BasemapStyle.ArcGISTopographic).apply {
    initialViewpoint = Viewpoint(
    latitude = 34.0270,
    longitude = -118.8050,
    scale = 72000.0
    )
    operationalLayers.add(featureLayer)
    }
    }
    /**
    * Query the [serviceFeatureTable] based on the [whereExpression] on the given
    * [queryExtent] and select the resulting features on the [featureLayer]
    */
    suspend fun queryFeatureLayer(
    context: Context,
    serviceFeatureTable: ServiceFeatureTable,
    featureLayer: FeatureLayer,
    whereExpression: String,
    queryExtent: Envelope?
    ) {
    // Clear any previous selections.
    featureLayer.clearSelection()
    // Create query parameters with the where expression and the current extent
    // and have geometry values returned in the results.
    val queryParameters = QueryParameters().apply {
    whereClause = whereExpression
    returnGeometry = true
    geometry = queryExtent
    }
    try {
    // Query the feature table with the query parameters.
    val featureQueryResult = serviceFeatureTable.queryFeatures(queryParameters).getOrThrow()
    // Iterate through the result and select the features on the feature layer.
    val resultIterator = featureQueryResult.iterator()
    if (resultIterator.hasNext()) {
    resultIterator.forEach { feature ->
    featureLayer.selectFeature(feature)
    }
    } else {
    showMessage(
    context,
    "No parcels found in the current extent, using Where expression: $whereExpression"
    )
    }
    } catch (e: Exception) {
    showMessage(context, "Feature search failed for: $whereExpression, ${e.message}")
    }
    }
    fun showMessage(context: Context, message: String) {
    Toast.makeText(context, message, Toast.LENGTH_LONG).show()
    }
  5. (Optional) The code in this tutorial calls a function to display messages to the user. One possible implementation of showMessage() is the following.

    MainScreen.kt
    207 collapsed lines
    @file:OptIn(ExperimentalMaterial3Api::class)
    package com.example.app.screens
    import android.content.Context
    import android.widget.Toast
    import androidx.compose.foundation.layout.Column
    import androidx.compose.foundation.layout.fillMaxSize
    import androidx.compose.foundation.layout.fillMaxWidth
    import androidx.compose.foundation.layout.padding
    import androidx.compose.material3.DropdownMenuItem
    import androidx.compose.material3.ExperimentalMaterial3Api
    import androidx.compose.material3.ExposedDropdownMenuBox
    import androidx.compose.material3.MenuAnchorType
    import androidx.compose.material3.Scaffold
    import androidx.compose.material3.Text
    import androidx.compose.material3.TextField
    import androidx.compose.material3.TopAppBar
    import androidx.compose.runtime.Composable
    import androidx.compose.runtime.mutableStateOf
    import androidx.compose.runtime.remember
    import androidx.compose.runtime.rememberCoroutineScope
    import androidx.compose.ui.Modifier
    import androidx.compose.ui.platform.LocalContext
    import androidx.compose.ui.res.stringResource
    import com.arcgismaps.data.QueryParameters
    import com.arcgismaps.data.ServiceFeatureTable
    import com.arcgismaps.geometry.Envelope
    import com.arcgismaps.mapping.ArcGISMap
    import com.arcgismaps.mapping.BasemapStyle
    import com.arcgismaps.mapping.Viewpoint
    import com.arcgismaps.mapping.layers.FeatureLayer
    import com.arcgismaps.toolkit.geoviewcompose.MapView
    import com.example.app.R
    import kotlinx.coroutines.Job
    import kotlinx.coroutines.launch
    @Composable
    fun MainScreen() {
    val context = LocalContext.current
    val coroutineScope = rememberCoroutineScope()
    val currentQueryJob = remember { mutableStateOf<Job?>(null) }
    // Store the current viewpoint geometry extent of the map.
    val currentExtent = remember { mutableStateOf<Envelope?>(null) }
    // Create a service feature table from a Los Angeles County parcels feature service.
    val serviceFeatureTable = ServiceFeatureTable(
    uri = "https://services3.arcgis.com/GVgbJbqm8hXASVYi/arcgis/rest/services/LA_County_Parcels/FeatureServer/0"
    )
    val featureLayer = remember { FeatureLayer.createWithFeatureTable(serviceFeatureTable) }
    val map = remember {
    createMap(featureLayer)
    }
    Scaffold(
    topBar = { TopAppBar(title = { Text(text = stringResource(id = R.string.app_name)) }) }
    ) {
    Column(
    Modifier.fillMaxSize().padding(it)
    ) {
    QueryDropDownMenu(
    onItemClicked = { sqlQueryExpression ->
    // Cancel the previous query job if it exists.
    currentQueryJob.value?.cancel()
    currentQueryJob.value = coroutineScope.launch {
    queryFeatureLayer(
    context = context,
    serviceFeatureTable = serviceFeatureTable,
    featureLayer = featureLayer,
    whereExpression = sqlQueryExpression,
    queryExtent = currentExtent.value
    )
    }
    })
    MapView(
    modifier = Modifier.fillMaxSize(),
    arcGISMap = map,
    onViewpointChangedForBoundingGeometry = { viewpoint ->
    currentExtent.value = viewpoint.targetGeometry.extent
    }
    )
    }
    }
    }
    @Composable
    fun QueryDropDownMenu(onItemClicked: (String) -> Unit) {
    val expanded = remember { mutableStateOf(false) }
    var selectedText = remember { mutableStateOf("") }
    val options = listOf(
    "UseType = \'Government\'",
    "UseType = \'Residential\'",
    "UseType = \'Irrigated Farm\'",
    "TaxRateArea = 10853",
    "TaxRateArea = 10860",
    "Roll_LandValue > 1000000",
    "Roll_LandValue < 1000000"
    )
    ExposedDropdownMenuBox(
    expanded = expanded.value,
    onExpandedChange = {
    expanded.value = !expanded.value
    }
    ) {
    TextField(
    modifier = Modifier.menuAnchor(type = MenuAnchorType.PrimaryNotEditable, enabled = true),
    value = selectedText.value,
    onValueChange = {},
    readOnly = true,
    label = { Text("Select a query expression") }
    )
    ExposedDropdownMenu(
    expanded = expanded.value,
    onDismissRequest = {
    expanded.value = false
    }
    ) {
    options.forEach { selectionOption ->
    DropdownMenuItem(
    text = { Text(text = selectionOption) },
    onClick = {
    selectedText.value = selectionOption
    expanded.value = false
    onItemClicked(selectedText.value)
    }
    )
    }
    }
    }
    }
    fun createMap(featureLayer: FeatureLayer): ArcGISMap {
    return ArcGISMap(BasemapStyle.ArcGISTopographic).apply {
    initialViewpoint = Viewpoint(
    latitude = 34.0270,
    longitude = -118.8050,
    scale = 72000.0
    )
    operationalLayers.add(featureLayer)
    }
    }
    /**
    * Query the [serviceFeatureTable] based on the [whereExpression] on the given
    * [queryExtent] and select the resulting features on the [featureLayer]
    */
    suspend fun queryFeatureLayer(
    context: Context,
    serviceFeatureTable: ServiceFeatureTable,
    featureLayer: FeatureLayer,
    whereExpression: String,
    queryExtent: Envelope?
    ) {
    // Clear any previous selections.
    featureLayer.clearSelection()
    // Create query parameters with the where expression and the current extent
    // and have geometry values returned in the results.
    val queryParameters = QueryParameters().apply {
    whereClause = whereExpression
    returnGeometry = true
    geometry = queryExtent
    }
    try {
    // Query the feature table with the query parameters.
    val featureQueryResult = serviceFeatureTable.queryFeatures(queryParameters).getOrThrow()
    // Iterate through the result and select the features on the feature layer.
    val resultIterator = featureQueryResult.iterator()
    if (resultIterator.hasNext()) {
    resultIterator.forEach { feature ->
    featureLayer.selectFeature(feature)
    }
    } else {
    showMessage(
    context,
    "No parcels found in the current extent, using Where expression: $whereExpression"
    )
    }
    } catch (e: Exception) {
    showMessage(context, "Feature search failed for: $whereExpression, ${e.message}")
    }
    }
    fun showMessage(context: Context, message: String) {
    Toast.makeText(context, message, Toast.LENGTH_LONG).show()
    }
  6. Click Run > Run > app to run the app.

The app loads with the map centered on the Santa Monica Mountains in California with the parcels feature layer displayed. Choose an attribute expression, and parcels in the current extent that meet the selected criteria will display in the specified selection color.

Alternatively, you can download the tutorial solution, as follows.

Option 2: Download the solution

  1. Click the Download solution link in the right-hand side of this page.

  2. Unzip the file to a location on your machine.

  3. Run Android Studio.

  4. Go to File > Open…. Navigate to the solution folder and click Open.

    On Windows: If you are in the Welcome to Android Studio dialog, click Open and navigate to the solution folder. Then click Open.

Since the downloaded solution does not contain authentication credentials, you must first set up authentication to create credentials, and then add the developer credentials to the solution.

Set up authentication

To access the secure ArcGIS location services ArcGIS Location Services, also referred to as Location Services, are services hosted by Esri that provide geospatial functionality for developing mapping applications. They include the ArcGIS Basemap Styles service, ArcGIS Static Basemap Tiles service, ArcGIS Places service, ArcGIS Geocoding service, ArcGIS Routing service, ArcGIS GeoEnrichment service, and ArcGIS Elevation service. An ArcGIS Location Platform or ArcGIS Online account is required to use the services. Learn more used in this tutorial, you must implement API key authentication API key authentication is a type of authentication that uses an API key to authenticate requests to ArcGIS services and secure portal items. Learn more or user authentication User authentication is a type of authentication that allows users with an ArcGIS account to sign into an application and allow it to access ArcGIS content, services, and resources on their behalf. The typical authorization protocol used is OAuth2.0. Learn more using an ArcGIS Location Platform An ArcGIS Location Platform account, formerly known as an ArcGIS Developer account, is an identity associated with an ArcGIS Location Platform subscription. Learn more or an ArcGIS Online An ArcGIS Online account, also known as an ArcGIS Organization account, is an identity associated with an ArcGIS Online subscription. It can be used to access ArcGIS tools and develop applications with ArcGIS location services for an organization. Learn more account.

To complete this tutorial, click on the tab in the switcher below for your authentication type of choice, either API key authentication or User authentication.

Create a new API key access token An access token is an authorization string that provides access to secure ArcGIS content, data, and services. Its capabilities are determined by the privileges it supports. It is obtained by implementing API key authentication, User authentication, or App authentication. Learn more with privileges Privileges are a set of permissions assigned to ArcGIS accounts, developer credentials, and applications that grant access to secure resources and functionality in ArcGIS. Learn more to access the secure resources used in this tutorial.

  1. Complete the Create an API key tutorial and create an API key with the following privilege(s) Privileges are a set of permissions assigned to ArcGIS accounts, developer credentials, and applications that grant access to secure resources and functionality in ArcGIS. Learn more :

    • Privileges
      • Location services > Basemaps
  2. Copy and paste the API key access token into a safe location. It will be used in a later step.

Set developer credentials in the solution

To allow your app users to access ArcGIS location services ArcGIS Location Services, also referred to as Location Services, are services hosted by Esri that provide geospatial functionality for developing mapping applications. They include the ArcGIS Basemap Styles service, ArcGIS Static Basemap Tiles service, ArcGIS Places service, ArcGIS Geocoding service, ArcGIS Routing service, ArcGIS GeoEnrichment service, and ArcGIS Elevation service. An ArcGIS Location Platform or ArcGIS Online account is required to use the services. Learn more , use the developer credentials that you created in the Set up authentication step to authenticate requests for resources.

  1. In the Android view of Android Studio, open app > kotlin+java > com.example.app > MainActivity. Set the AuthenticationMode to .API_KEY.

    MainActivity.kt
    14 collapsed lines
    package com.example.app
    import android.os.Bundle
    import androidx.activity.ComponentActivity
    import androidx.activity.compose.setContent
    import androidx.activity.enableEdgeToEdge
    import com.arcgismaps.ApiKey
    import com.arcgismaps.ArcGISEnvironment
    import com.arcgismaps.httpcore.authentication.OAuthUserConfiguration
    import com.arcgismaps.toolkit.authentication.AuthenticatorState
    import com.arcgismaps.toolkit.authentication.DialogAuthenticator
    import com.example.app.screens.MainScreen
    import com.example.app.ui.theme.TutorialTheme
    class MainActivity : ComponentActivity() {
    private enum class AuthenticationMode { API_KEY, USER_AUTH }
    private val authenticationMode = AuthenticationMode.API_KEY
    42 collapsed lines
    private val authenticatorState = AuthenticatorState()
    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    when (authenticationMode) {
    AuthenticationMode.API_KEY -> {
    ArcGISEnvironment.apiKey = ApiKey.create("YOUR_ACCESS_TOKEN")
    }
    AuthenticationMode.USER_AUTH -> {
    authenticatorState.oAuthUserConfigurations = listOf(
    OAuthUserConfiguration(
    portalUrl = "https://www.arcgis.com",
    clientId = "YOUR_CLIENT_ID",
    redirectUrl = "YOUR_REDIRECT_URL"
    )
    )
    }
    }
    enableEdgeToEdge()
    setContent {
    TutorialTheme {
    MainScreen()
    if (authenticationMode == AuthenticationMode.USER_AUTH) {
    DialogAuthenticator(authenticatorState)
    }
    }
    }
    }
    }
  2. Set the apiKey property with your API key access token.

    MainActivity.kt
    22 collapsed lines
    package com.example.app
    import android.os.Bundle
    import androidx.activity.ComponentActivity
    import androidx.activity.compose.setContent
    import androidx.activity.enableEdgeToEdge
    import com.arcgismaps.ApiKey
    import com.arcgismaps.ArcGISEnvironment
    import com.arcgismaps.httpcore.authentication.OAuthUserConfiguration
    import com.arcgismaps.toolkit.authentication.AuthenticatorState
    import com.arcgismaps.toolkit.authentication.DialogAuthenticator
    import com.example.app.screens.MainScreen
    import com.example.app.ui.theme.TutorialTheme
    class MainActivity : ComponentActivity() {
    private enum class AuthenticationMode { API_KEY, USER_AUTH }
    private val authenticationMode = AuthenticationMode.API_KEY
    private val authenticatorState = AuthenticatorState()
    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    when (authenticationMode) {
    AuthenticationMode.API_KEY -> {
    ArcGISEnvironment.apiKey = ApiKey.create("YOUR_ACCESS_TOKEN")
    }
    30 collapsed lines
    AuthenticationMode.USER_AUTH -> {
    authenticatorState.oAuthUserConfigurations = listOf(
    OAuthUserConfiguration(
    portalUrl = "https://www.arcgis.com",
    clientId = "YOUR_CLIENT_ID",
    redirectUrl = "YOUR_REDIRECT_URL"
    )
    )
    }
    }
    enableEdgeToEdge()
    setContent {
    TutorialTheme {
    MainScreen()
    if (authenticationMode == AuthenticationMode.USER_AUTH) {
    DialogAuthenticator(authenticatorState)
    }
    }
    }
    }
    }

Best Practice: The access token is stored directly in the code as a convenience for this tutorial. Do not store credentials directly in source code in a production environment.

Run the app

Click Run > Run > app to run the app.

The app loads with the map centered on the Santa Monica Mountains in California with the parcels feature layer displayed. Choose an attribute expression, and parcels in the current extent that meet the selected criteria will display in the specified selection color.

What’s next?

Learn how to use additional API features, ArcGIS location services, and ArcGIS tools in these tutorials: