Query features with arcade expression

View on GitHubSample viewer app

Query features on a map using an Arcade expression.

QueryFeaturesWithArcadeExpression

Use case

Arcade is a portable, lightweight, and secure expression language used to create custom content in ArcGIS applications. Like other expression languages, it can perform mathematical calculations, manipulate text, and evaluate logical statements. It also supports multi-statement expressions, variables, and flow control statements. What makes Arcade particularly unique when compared to other expression and scripting languages is its inclusion of feature and geometry data types. This sample uses an Arcade expression to query the number of crimes in a neighborhood in the last 60 days.

How to use the sample

Tap on any neighborhood to see the number of crimes in the last 60 days in a TextView.

How it works

  1. Create a PortalItem using the URL and ID.

  2. Create an ArcGISMap using the portal item.

  3. Set up a listener for taps on the map.

  4. Identify the visible layer where it is tapped using mapView.identifyLayer() and get the feature.

  5. Create the following ArcadeExpression:

    expressionValue = "var crimes = FeatureSetByName(\$map, 'Crime in the last 60 days');\n" +
     "return Count(Intersects(\$feature, crimes));"
  6. Create an ArcadeEvaluator using the Arcade expression and ArcadeProfile.FormCalculation.

  7. Create a map of profile variables with the following key-value pairs:

     mapOf<String, Any>("\$feature" to feature, "\$map" to mapView.map)
  8. Call ArcadeEvaluator.evaluate() on the Arcade evaluator object and pass the profile variables map.

  9. Get the ArcadeEvaluationResult.result.

  10. Convert the result to a numerical value (integer) and populate the UI with the crime count.

Relevant API

  • ArcadeEvaluationResult
  • ArcadeEvaluator
  • ArcadeExpression
  • ArcadeProfile
  • Portal
  • PortalItem

About the data

This sample uses the Crimes in Police Beats Sample ArcGIS Online Web Map which contains 2 layers for city beats borders, and crimes in the last 60 days as recorded by the Rochester, NY police department.

Additional information

Visit Getting Started on the ArcGIS Developer website to learn more about Arcade expressions.

Tags

Arcade evaluator, Arcade expression, identify layers, portal, portal item, query

Sample Code

MainActivity.kt
Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
/*
 * Copyright 2023 Esri
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.esri.arcgismaps.sample.queryfeatureswitharcadeexpression

import android.graphics.BitmapFactory
import android.graphics.drawable.BitmapDrawable
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.lifecycleScope
import com.arcgismaps.ApiKey
import com.arcgismaps.ArcGISEnvironment
import com.arcgismaps.arcade.ArcadeEvaluator
import com.arcgismaps.arcade.ArcadeExpression
import com.arcgismaps.arcade.ArcadeProfile
import com.arcgismaps.data.ArcGISFeature
import com.arcgismaps.mapping.ArcGISMap
import com.arcgismaps.mapping.layers.Layer
import com.arcgismaps.mapping.symbology.PictureMarkerSymbol
import com.arcgismaps.mapping.view.Graphic
import com.arcgismaps.mapping.view.GraphicsOverlay
import com.arcgismaps.mapping.view.ScreenCoordinate
import com.arcgismaps.portal.Portal
import com.arcgismaps.mapping.PortalItem
import com.esri.arcgismaps.sample.queryfeatureswitharcadeexpression.databinding.ActivityMainBinding
import com.google.android.material.snackbar.Snackbar
import kotlinx.coroutines.launch

class MainActivity : AppCompatActivity() {

    // set up data binding for the activity
    private val activityMainBinding: ActivityMainBinding by lazy {
        DataBindingUtil.setContentView(this, R.layout.activity_main)
    }

    private val mapView by lazy {
        activityMainBinding.mapView
    }

    private val infoTextView by lazy {
        activityMainBinding.infoTextView
    }

    // progress indicator
    private val progressBar by lazy {
        activityMainBinding.progressBar
    }

    // setup the red pin marker image as a bitmap drawable
    private val markerDrawable: BitmapDrawable by lazy {
        // load the bitmap from resources and create a drawable
        val bitmap = BitmapFactory.decodeResource(resources, R.drawable.map_pin_symbol)
        BitmapDrawable(resources, bitmap)
    }

    // setup the red pin marker as a Graphic
    private val markerGraphic: Graphic by lazy {
        // creates a symbol from the marker drawable
        val markerSymbol = PictureMarkerSymbol.createWithImage(markerDrawable).apply {
            // resize the symbol into a smaller size
            width = 30f
            height = 30f
            // offset in +y axis so the marker spawned is right on the touch point
            offsetY = 25f
        }
        // create the graphic from the symbol
        Graphic(symbol = markerSymbol)
    }

    // create a graphic overlay
    private val graphicsOverlay = GraphicsOverlay()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // authentication with an API key or named user is
        // required to access basemaps and other location services
        ArcGISEnvironment.apiKey = ApiKey.create(BuildConfig.API_KEY)
        lifecycle.addObserver(mapView)

        // create a portal item with the itemId of the web map
        val portal = Portal("https://www.arcgis.com/")
        val portalItem = PortalItem(portal, "539d93de54c7422f88f69bfac2aebf7d")
        // create and add a map with with portal item
        val map = ArcGISMap(portalItem)
        // add the marker graphic to the graphics overlay
        graphicsOverlay.graphics.add(markerGraphic)
        mapView.apply {
            this.map = map
            // add the graphics overlay to the MapView
            graphicsOverlays.add(graphicsOverlay)
        }

        lifecycleScope.launch {
            // show an error and return if the map load failed
            map.load().onFailure {
                return@launch showError("Error loading map:${it.message}")
            }

            // get the RPD Beats layer from the map's operational layers
            val policeBeatsLayer = map.operationalLayers.firstOrNull { layer ->
                    layer.id == "RPD_Reorg_9254"
                } ?: return@launch showError("Error finding RPD Beats layer")

            // capture and collect when the user taps on the screen
            mapView.onSingleTapConfirmed.collect { event ->
                // update the marker location to where the user tapped on the map
                event.mapPoint?.let { point ->
                    markerGraphic.geometry = point
                    mapView.setViewpointCenter(point)
                }
                // evaluate an Arcade expression on the tapped screen coordinate
                evaluateArcadeExpression(event.screenCoordinate, map, policeBeatsLayer)
            }
        }
    }

    /**
     * Evaluates an Arcade expression that returns crime in the last 60 days at the tapped
     * [screenCoordinate] on the [map] with the [policeBeatsLayer] and displays the result
     * in a textview
     */
    private suspend fun evaluateArcadeExpression(
        screenCoordinate: ScreenCoordinate,
        map: ArcGISMap,
        policeBeatsLayer: Layer
    ) {
        // show the progress indicator as the Arcade evaluation can take time to complete
        progressBar.visibility = View.VISIBLE
        // identify the layer and its elements based on the position tapped on the mapView and
        // get the result
        val result = mapView.identifyLayer(
            layer = policeBeatsLayer,
            screenCoordinate = screenCoordinate,
            tolerance = 12.0,
            returnPopupsOnly = false
        )
        // get the result as an IdentifyLayerResult
        val identifyLayerResult = result.getOrElse { error ->
            // if the identifyLayer operation failed show an error and return
            showError("Error identifying layer:${error.message}")
            // reset the text view to show its default text
            infoTextView.text = getString(R.string.tap_to_begin)
            // dismiss the progress indicator
            progressBar.visibility = View.GONE
            return
        }
        // if there are no geoElements identified
        if (identifyLayerResult.geoElements.isEmpty()) {
            // since the layer is a feature layer, display that no features were found
            infoTextView.text = getString(R.string.no_features_found)
            // dismiss the progress indicator
            progressBar.visibility = View.GONE
            return
        }
        // get the first identified GeoElement as an ArcGISFeature
        val identifiedFeature = identifyLayerResult.geoElements.first() as ArcGISFeature
        // create a string containing the Arcade expression
        val expressionValue =
            "var crimes = FeatureSetByName(\$map, 'Crime in the last 60 days');\n" +
                "return Count(Intersects(\$feature, crimes));"
        // create an ArcadeExpression using the string expression
        val arcadeExpression = ArcadeExpression(expressionValue)
        // create an ArcadeEvaluator with the ArcadeExpression and an ArcadeProfile
        val arcadeEvaluator = ArcadeEvaluator(arcadeExpression, ArcadeProfile.FormCalculation)
        //  create a map of profile variables with the feature and map as key value pairs
        val profileVariables = mapOf<String, Any>("\$feature" to identifiedFeature, "\$map" to map)
        // evaluate using the previously set profile variables and get the result
        val evaluationResult = arcadeEvaluator.evaluate(profileVariables)
        // get the result as an ArcadeEvaluationResult
        val arcadeEvaluationResult = evaluationResult.getOrElse { error ->
            // if the evaluation failed show an error and return
            showError("Error evaluating Arcade expression:${error.message}")
            // reset the text view to show its default text
            infoTextView.text = getString(R.string.tap_to_begin)
            // dismiss the progress indicator
            progressBar.visibility = View.GONE
            return
        }
        // get the crimes count from the arcadeEvaluationResult as a numerical double value
        val crimesCount = arcadeEvaluationResult.result as Double
        // display this result in a textview
        infoTextView.text = getString(R.string.crime_info_text, crimesCount.toInt())
        // hide the progress indicator
        progressBar.visibility = View.GONE
    }

    private fun showError(message: String) {
        Log.e(localClassName, message)
        Snackbar.make(mapView, message, Snackbar.LENGTH_SHORT).show()
    }
}

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