Statistical query

View on GitHubSample viewer app

Query a table to get aggregated statistics back for a specific field.

Statistical query results

Use case

For example, a county boundaries table with population information can be queried to return aggregated results for total, average, maximum, and minimum population, rather than downloading the values for every county and calculating statistics manually.

How to use the sample

Pan and zoom to define the extent for the query. Use the "Cities in current extent" checkbox to control whether the query only includes features in the visible extent. Use the "Cities greater than 5M" checkbox to filter the results to only those cities with a population greater than 5 million people. Tap "Get statistics" to perform the query. The query will return population-based statistics from the combined results of all features matching the query criteria.

How it works

  1. Create an AGSServiceFeatureTable with a URL to the feature service.
  2. Create AGSStatisticsQueryParameters using an array of AGSStatisticDefinition objects.
  3. Pass in the parameters into AGSFeatureTable.queryStatistics(with:completion:). Depending on the state of the two checkboxes, additional parameters are set.
  4. Use AGSStatisticsQueryResult.statisticRecordEnumerator() on the first returned AGSStatisticsQueryResult to display each AGSStatisticRecord.

Relevant API

  • AGSServiceFeatureTable
  • AGSStatisticDefinition
  • AGSStatisticRecord
  • AGSStatisticsQueryParameters
  • AGSStatisticsQueryResult
  • AGSStatisticType

Tags

analysis, average, bounding geometry, filter, intersect, maximum, mean, minimum, query, spatial query, standard deviation, statistics, sum, variance

Sample Code

StatisticalQueryViewController.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
// Copyright 2017 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.

import UIKit
import ArcGIS

class StatisticalQueryViewController: UIViewController {
    @IBOutlet private weak var mapView: AGSMapView!
    @IBOutlet private var visualEffectView: UIVisualEffectView!
    @IBOutlet private var getStatisticsButton: UIButton!
    @IBOutlet private var onlyInCurrentExtentSwitch: UISwitch!
    @IBOutlet private var onlyBigCitiesSwitch: UISwitch!
    private var map: AGSMap?
    private var serviceFeatureTable: AGSServiceFeatureTable?

    override func viewDidLoad() {
        super.viewDidLoad()

        // Add the source code button item to the right of navigation bar
        (navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["StatisticalQueryViewController"]

        // Constraint visual effect view to the map view's attribution label
        visualEffectView.bottomAnchor.constraint(equalTo: mapView.attributionTopAnchor, constant: -10.0).isActive = true

        // Corner radius for button
        getStatisticsButton.layer.cornerRadius = 10

        // Initialize map and set it on map view
        map = AGSMap(basemapStyle: .arcGISStreets)
        mapView.map = map

        // Initialize feature table, layer and add it to map
        serviceFeatureTable = AGSServiceFeatureTable(url: URL(string: "https://sampleserver6.arcgisonline.com/arcgis/rest/services/SampleWorldCities/MapServer/0")!)
        let featureLayer = AGSFeatureLayer(featureTable: serviceFeatureTable!)
        map?.operationalLayers.add(featureLayer)
    }

    // MARK: Actions

    @IBAction private func getStatisticsAction(_ sender: Any) {
        //
        // Add the statistic definitions
        var statisticDefinitions = [AGSStatisticDefinition]()
        statisticDefinitions.append(AGSStatisticDefinition(onFieldName: "POP", statisticType: .average, outputAlias: nil))
        statisticDefinitions.append(AGSStatisticDefinition(onFieldName: "POP", statisticType: .minimum, outputAlias: nil))
        statisticDefinitions.append(AGSStatisticDefinition(onFieldName: "POP", statisticType: .maximum, outputAlias: nil))
        statisticDefinitions.append(AGSStatisticDefinition(onFieldName: "POP", statisticType: .sum, outputAlias: nil))
        statisticDefinitions.append(AGSStatisticDefinition(onFieldName: "POP", statisticType: .standardDeviation, outputAlias: nil))
        statisticDefinitions.append(AGSStatisticDefinition(onFieldName: "POP", statisticType: .variance, outputAlias: nil))
        statisticDefinitions.append(AGSStatisticDefinition(onFieldName: "POP", statisticType: .count, outputAlias: nil))

        // Create the parameters with statistic definitions
        let statisticsQueryParameters = AGSStatisticsQueryParameters(statisticDefinitions: statisticDefinitions)

        // If only using features in the current extent, set up the spatial filter for the statistics query parameters
        if onlyInCurrentExtentSwitch.isOn {
            //
            // Set the statistics query parameters geometry with the envelope
            statisticsQueryParameters.geometry = mapView.visibleArea?.extent

            // Set the spatial relationship to Intersects (which is the default)
            statisticsQueryParameters.spatialRelationship = .intersects
        }

        // If only evaluating the largest cities (over 5 million in population), set up an attribute filter
        if onlyBigCitiesSwitch.isOn {
            statisticsQueryParameters.whereClause = "POP_RANK = 1"
        }

        // Execute the statistical query with parameters
        serviceFeatureTable?.queryStatistics(with: statisticsQueryParameters) { [weak self] (statisticsQueryResult, error) in
            //
            // If there an error, display it
            guard error == nil else {
                self?.presentAlert(error: error!)
                return
            }

            // Get the result
            if let statisticRecordEnumerator = statisticsQueryResult?.statisticRecordEnumerator() {
                //
                // Let's build result message
                var resultMessage = " \n"
                while statisticRecordEnumerator.hasNextObject() {
                    let statisticRecord = statisticRecordEnumerator.nextObject()
                    for (key, value) in (statisticRecord?.statistics)! {
                        resultMessage += "\(key): \(value) \n"
                    }
                }

                // Show result
                self?.presentAlert(title: "Statistical Query Results", message: resultMessage)
            }
        }
    }
}

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