Query features with Arcade expression

View on GitHubSample viewer app

Query features on a map using an Arcade expression.

Query features with Arcade expression

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

How it works

  1. Create an AGSPortalItem using the portal and ID.

  2. Create an AGSMap using the portal item.

  3. Set the AGSGeoViewTouchDelegate to the map.

  4. Identify the layers tapped on the map view with AGSGeoView.identifyLayers(atScreenPoint:tolerance:returnPopupsOnly:completion:).

  5. Create the following AGSArcadeExpression:

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

  7. Create a dictionary of profile variables with the following pairs:

    {"$feature", identifiedFeature}

    {"$map", map}

  8. Use AGSArcadeEvaluator.evaluate(withProfileVariables:completion:) with the profile variables to evaluate the Arcade expression.

  9. Convert the result to a String to display the crime count in a callout.

Relevant API

  • AGSArcadeEvaluationResult
  • AGSArcadeEvaluator
  • AGSArcadeExpression
  • AGSArcadeProfile
  • AGSPortal
  • AGSPortalItem

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

QueryFeaturesArcadeExpressionViewController.swift
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
// 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
//
//   https://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.

import UIKit
import ArcGIS

class QueryFeaturesArcadeExpressionViewController: UIViewController {
    @IBOutlet var mapView: AGSMapView! {
        didSet {
            mapView.map = makeMap()
            // Set the touch delegate.
            mapView.touchDelegate = self
        }
    }

    /// The Arcade expression evaluation operation.
    var evaluateOperation: AGSCancelable?
    /// The evaluator to evaluate an `AGSArcadeExpression` under a given
    /// `AGSArcadeProfile`.
    var evaluator: AGSArcadeEvaluator?
    /// Make and load a map.
    func makeMap() -> AGSMap {
        // Create a portal item with the portal and item ID.
        let portalItem = AGSPortalItem(portal: .arcGISOnline(withLoginRequired: false), itemID: "539d93de54c7422f88f69bfac2aebf7d")
        // Make a map with the portal item.
        let map = AGSMap(item: portalItem)
        return map
    }

    /// Evaluate the Arcade expression for the selected feature at the map point.
    func evaluateArcadeInCallout(for feature: AGSArcGISFeature, at mapPoint: AGSPoint) {
        guard let map = mapView.map else { return }
        evaluateOperation?.cancel()
        // Instantiate a string containing the Arcade expression.
        let expressionValue =
        """
        var crimes = FeatureSetByName($map, 'Crime in the last 60 days');
        return Count(Intersects($feature, crimes));
        """
        // Create an Arcade expression using the string.
        let expression = AGSArcadeExpression(expression: expressionValue)
        // Create an Arcade evaluator with the Arcade expression and an Arcade profile.
        evaluator = AGSArcadeEvaluator(expression: expression, profile: .formCalculation)
        let profileVariables = ["$feature": feature, "$map": map]
        // Show progress hud.
        UIApplication.shared.showProgressHUD(message: "Evaluating")
        // Get the Arcade evaluation result given the previously set profile variables.
        evaluateOperation = evaluator!.evaluate(withProfileVariables: profileVariables) { [weak self] result, error in
            // Dismiss progress hud.
            UIApplication.shared.hideProgressHUD()
            guard let self = self else { return }
            self.evaluateOperation = nil
            self.evaluator = nil
            if let result = result, let crimeCount = result.cast(to: .string) as? String {
                self.mapView.setViewpointCenter(mapPoint)
                // Hide the accessory button.
                self.mapView.callout.isAccessoryButtonHidden = true
                // Set the detail text.
                self.mapView.callout.detail = String(format: "Crimes in the last 60 days: %@", crimeCount)
                // Prompt the callout at the map point.
                self.mapView.callout.show(for: feature, tapLocation: mapPoint, animated: true)
            } else if let error = error {
                // Present an error if needed.
                self.presentAlert(error: error)
            }
        }
    }

    // MARK: UIViewController

    override func viewDidLoad() {
        super.viewDidLoad()
        // Add the source code button item to the right of navigation bar.
        (navigationItem.rightBarButtonItem as? SourceCodeBarButtonItem)?.filenames = [
            "QueryFeaturesArcadeExpressionViewController"
        ]
    }
}

// MARK: - AGSGeoViewTouchDelegate

extension QueryFeaturesArcadeExpressionViewController: AGSGeoViewTouchDelegate {
    func geoView(_ geoView: AGSGeoView, didTapAtScreenPoint screenPoint: CGPoint, mapPoint: AGSPoint) {
        // Dismiss any presenting callout.
        mapView.callout.dismiss()
        // Identify features at the tapped location.
        mapView.identifyLayers(atScreenPoint: screenPoint, tolerance: 12, returnPopupsOnly: false) { [weak self] results, error in
            guard let self = self else { return }
            // Get the selected feature.
            if let elements = results?.first?.geoElements, let identifiedFeature = elements.first as? AGSArcGISFeature {
                // Evaluate the Arcade for the given feature.
                self.evaluateArcadeInCallout(for: identifiedFeature, at: mapPoint)
            } else if let error = error {
                // Present an error alert if needed.
                self.presentAlert(error: error)
            }
        }
    }
}

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