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

Click on any neighborhood to see the number of crimes in the last 60 days in a callout.

How it works

  1. Create a Portal using the URL.
  2. Create a PortalItem using the Portal and ID.
  3. Create an ArcGISMap using the PortalItem.
  4. Set up a listener for clicks on the map.
  5. Identify the visible layer where it is clicked using mapView.identifyLayerAsync() and get the feature.
  6. Create the following ArcadeExpression: new ArcadeExpression("var crimes = FeatureSetByName(\$map, 'Crime in the last 60 days');\n" + "return Count(Intersects(\$feature, crimes));");
  7. Create an ArcadeEvaluator using the Arcade expression and ArcadeProfile.FORM_CALCULATION.
  8. Create a map of profile variables with $feature and $map as keys.
  9. Call arcadeEvaluator.evaluateAsync() and pass it the profile variables map as parameters.
  10. Once the evaluateAsync() has finished evaluating, get the ArcadeEvaluationResult with listenableFuture.get()
  11. Get the result from the arcade evaluation result with arcadeEvaluationResult.getResult().
  12. Convert the result to a numerical value (integer) and populate the callout 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

QueryFeaturesWithArcadeExpressionSample.java
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
/*
 * Copyright 2022 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.samples.query_features_with_arcade_expression;

import java.util.HashMap;

import javafx.application.Application;
import javafx.geometry.Point2D;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

import com.esri.arcgisruntime.ArcGISRuntimeEnvironment;
import com.esri.arcgisruntime.arcade.ArcadeEvaluationResult;
import com.esri.arcgisruntime.arcade.ArcadeEvaluator;
import com.esri.arcgisruntime.arcade.ArcadeExpression;
import com.esri.arcgisruntime.arcade.ArcadeProfile;
import com.esri.arcgisruntime.concurrent.ListenableFuture;
import com.esri.arcgisruntime.data.ArcGISFeature;
import com.esri.arcgisruntime.geometry.Point;
import com.esri.arcgisruntime.layers.Layer;
import com.esri.arcgisruntime.loadable.LoadStatus;
import com.esri.arcgisruntime.mapping.ArcGISMap;
import com.esri.arcgisruntime.mapping.view.Callout;
import com.esri.arcgisruntime.mapping.view.MapView;
import com.esri.arcgisruntime.portal.Portal;
import com.esri.arcgisruntime.portal.PortalItem;

public class QueryFeaturesWithArcadeExpressionSample extends Application {

  private MapView mapView;
  private ArcGISMap map;
  private final String calloutText = "Crimes in the last 60 days: ";

  @Override
  public void start(Stage stage) {
    try {
      // create stack pane and application scene
      var stackPane = new StackPane();
      var scene = new Scene(stackPane);

      // set title, size, and add scene to stage
      stage.setTitle("Query Features With Arcade Expression Sample");
      stage.setWidth(800);
      stage.setHeight(700);
      stage.setScene(scene);
      stage.show();

      // authentication with an API key or named user is required to access basemaps and other location services
      String yourAPIKey = System.getProperty("apiKey");
      ArcGISRuntimeEnvironment.setApiKey(yourAPIKey);

      // create a progress indicator
      var progressIndicator = new ProgressIndicator();

      // create a portal item and use it to create a map
      var portal = new Portal("https://www.arcgis.com/");
      var portalItem = new PortalItem(portal, "539d93de54c7422f88f69bfac2aebf7d");
      map = new ArcGISMap(portalItem);

      // create a map view and set the map to it
      mapView = new MapView();
      mapView.setMap(map);

      // set callout leader to appear at the bottom of the callout
      Callout callout = mapView.getCallout();
      callout.setLeaderPosition(Callout.LeaderPosition.BOTTOM);

      // wait for the map to finish loading data from portal before accessing its layers
      map.addDoneLoadingListener(() -> {
        if (map.getLoadStatus() == LoadStatus.LOADED) {
          Layer policeBeatsLayer = map.getOperationalLayers().get(0);
          progressIndicator.setVisible(false);

          // if map clicked, evaluate an arcade expression at that point
          mapView.setOnMouseClicked(event -> {
            if (event.getButton() == MouseButton.PRIMARY && event.isStillSincePress()) {
              // get the location of the click on the screen
              Point2D screenPoint = new Point2D(event.getX(), event.getY());

              // convert the click location from screen coordinates to map coordinates
              Point mapPoint = mapView.screenToLocation(screenPoint);

              // identify any features on the layer at the clicked location
              var identifyLayerResultFuture = mapView.identifyLayerAsync(policeBeatsLayer,
                screenPoint, 0, false);
              identifyLayerResultFuture.addDoneListener(() -> {
                if (identifyLayerResultFuture.isDone()) {
                  try {
                    var identifyLayerResult = identifyLayerResultFuture.get();

                    // only execute query if the police beats layer has data at the selected point
                    if (identifyLayerResult.getElements().size() != 0) {
                      ArcGISFeature feature = (ArcGISFeature) identifyLayerResult.getElements().get(0);

                      // show callout and text without data
                      callout.setTitle(calloutText);
                      callout.setDetail("...");
                      callout.showCalloutAt(mapPoint);
                      callout.setVisible(true);

                      // setup arcade expression and evaluator
                      String arcadeExpressionString = "var crimes = FeatureSetByName($map, 'Crime in the last 60 days');\n" +
                        "return Count(Intersects($feature, crimes));";
                      var arcadeExpression = new ArcadeExpression(arcadeExpressionString);
                      var arcadeEvaluator = new ArcadeEvaluator(arcadeExpression, ArcadeProfile.FORM_CALCULATION);

                      // instantiate key/value pairs
                      var hashMap = new HashMap<String, Object>();
                      hashMap.put("$feature", feature);
                      hashMap.put("$map", mapView.getMap());

                      // evaluate the arcade expression asynchronously
                      ListenableFuture<ArcadeEvaluationResult> resultFuture = arcadeEvaluator.evaluateAsync(hashMap);

                      // wait for the expression to finish evaluating before attempting to access it
                      resultFuture.addDoneListener(() -> {
                        if (resultFuture.isDone()) {
                          try {
                            // get result from async method and round
                            var arcadeEvaluationResult = resultFuture.get();
                            var crimesCount = Math.round((double) arcadeEvaluationResult.getResult());

                            // add data from arcade evaluation to callout
                            callout.setDetail(String.valueOf(crimesCount));
                          } catch (Exception e) {
                            throw new RuntimeException(e);
                          }
                        }
                      });

                    } else {
                      // if no data is found at the selected point, hide the callout
                      callout.setVisible(false);
                    }

                  } catch (Exception e) {
                    throw new RuntimeException(e);
                  }
                }
              });
            }
          });

        } else if (map.getLoadStatus() == LoadStatus.FAILED_TO_LOAD) {
          new Alert(Alert.AlertType.ERROR, "Map failed to load").show();
        }
      });

      // add the map view and progress indicator to the stack pane
      stackPane.getChildren().addAll(mapView, progressIndicator);
    } catch (Exception e) {
      // on any error, display the stack trace.
      e.printStackTrace();
    }
  }

  /**
   * Stops and releases all resources used in application.
   */
  @Override
  public void stop() {
    if (mapView != null) {
      mapView.dispose();
    }
  }

  /**
   * Opens and runs application.
   *
   * @param args arguments passed to this application
   */
  public static void main(String[] args) {
    Application.launch(args);
  }
}

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