Query feature count and extent

View on GitHub

Zoom to features matching a query and count the features in the current visible extent.

Image of Query feature count and extent sample

Use case

Queries can be used to search for features in a feature table using text entry. This is helpful for finding a specific feature by name in a large feature table. A query can also be used to count features in an extent. This could be used to count the number of traffic incidents in a particular region when working with an incident dataset for a larger area.

How to use the sample

Use the button Select State, then use the picker to zoom to the extent of the state specified. Use the button to count the features in the current extent.

How it works

Querying by state abbreviation:

  1. A QueryParameters object is created with a WhereClause.
  2. FeatureTable.QueryFeatures is called with the QueryParameters object to obtain the extent that contains all matching features.
  3. The extent is converted to a Viewpoint, which is passed to MapView.SetViewpointAsync.

Counting features in the current extent:

  1. The current visible extent is obtained from a call to MapView.onViewpointChanged(kind:).
  2. A QueryParameters object is created with the visible extent and a defined SpatialRelationship (in this case 'intersects').
  3. The count of matching features is obtained from a call to FeatureTable.QueryFeatureCount.

Relevant API

  • FeatureTable.QueryExtent
  • FeatureTable.QueryFeatureCount
  • MapView
  • QueryParameters
  • QueryParameters.Geometry
  • QueryParameters.SpatialRelationship
  • QueryParameters.WhereClause

About the data

See the Medicare Hospital Spending per Patient, 2016 layer on ArcGIS Online.

Hospitals in blue/turquoise spend less than the national average. Red/salmon indicates higher spending relative to other hospitals, while gray is average.

Tags

count, feature layer, feature table, features, filter, number, query

Sample Code

QueryFeatureCountAndExtentView.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
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
// Copyright 2024 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 ArcGIS
import SwiftUI

struct QueryFeatureCountAndExtentView: View {
    /// The view model for the sample.
    @StateObject private var model = Model()

    /// The currently selected state abbreviation.
    @State private var selectedState: String?

    /// A Boolean value indicating whether the feature count bar is showing.
    @State private var showFeatureCountBar = false

    /// The error shown in the error alert.
    @State private var error: Error?

    /// The current viewpoint of the map.
    @State private var viewpoint: Viewpoint?

    /// The count of features within the current viewpoint.
    @State private var featureCountResult: Int?

    var body: some View {
        MapViewReader { proxy in
            MapView(map: model.map)
                .onViewpointChanged(kind: .boundingGeometry) { newViewpoint in
                    // Update viewpoint when it changes.
                    viewpoint = newViewpoint
                }
                .task(id: selectedState) {
                    // Perform query and update the viewpoint when the selected state changes.
                    guard let state = selectedState else { return }
                    do {
                        if let combinedExtent = try await model.queryExtent(stateAbbreviation: state) {
                            await proxy.setViewpointGeometry(combinedExtent)
                            showFeatureCountBar = false
                        }
                    } catch {
                        self.error = error
                    }
                    selectedState = nil
                }
        }
        .overlay(alignment: .top) {
            if showFeatureCountBar {
                Text("\(featureCountResult ?? 0) feature(s) in extent")
                    .frame(maxWidth: .infinity)
                    .padding(.vertical, 6)
                    .background(.thinMaterial, ignoresSafeAreaEdges: .horizontal)
                    .transition(.move(edge: .top))
            }
        }
        .toolbar {
            ToolbarItemGroup(placement: .bottomBar) {
                // Menu to select a state.
                Menu("Select State") {
                    ForEach(model.stateAbbreviations, id: \.self) { abbreviation in
                        Button {
                            selectedState = abbreviation
                        } label: {
                            Text(abbreviation)
                        }
                    }
                }

                // Button to count features within the visible extent.
                Button("Count Features") {
                    Task {
                        do {
                            if let viewpoint = viewpoint {
                                featureCountResult = try await model.countFeaturesWithinExtent(extent: viewpoint.targetGeometry)
                                showFeatureCountBar = true
                            }
                        } catch {
                            self.error = error
                        }
                    }
                }
            }
        }
        .errorAlert(presentingError: $error)
    }
}

private extension QueryFeatureCountAndExtentView {
    /// The view model for the sample.
    @MainActor
    class Model: ObservableObject {
        /// The map with a basemap and initial viewpoint.
        let map: Map = {
            let map = Map(basemapStyle: .arcGISDarkGray)
            map.initialViewpoint = Viewpoint(
                center: Point(x: -11e6, y: 5e6, spatialReference: .webMercator),
                scale: 9e7
            )
            return map
        }()

        /// The layer that displays features on the map.
        private let featureLayer: FeatureLayer

        /// The table for querying features from a server.
        private let featureTable: ServiceFeatureTable

        /// The list of state abbreviations for selection.
        let stateAbbreviations = [
            "AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "DC", "FL", "GA", "HI",
            "ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MD", "MA", "MI", "MN",
            "MS", "MO", "MT", "NE", "NV", "NH", "NJ", "NM", "NY", "NC", "ND", "OH",
            "OK", "OR", "PA", "RI", "SC", "SD", "TN", "TX", "UT", "VT", "VA", "WA",
            "WV", "WI", "WY"
        ]

        init() {
            featureTable = ServiceFeatureTable(url: .medicareHospitalSpendLayer)
            featureLayer = FeatureLayer(featureTable: featureTable)
            map.addOperationalLayer(featureLayer)
        }

        /// Queries the extent for the specified state.
        /// - Parameter stateAbbreviation: The state abbreviation to query.
        /// - Returns: The combined extent of the queried features or `nil` if no features are found.
        /// - Throws: An error if the query fails.
        func queryExtent(stateAbbreviation: String) async throws -> Envelope? {
            guard !stateAbbreviation.isEmpty else { return nil }
            featureLayer.clearSelection()
            let queryParameters = QueryParameters()
            queryParameters.whereClause = "State LIKE '%\(stateAbbreviation)%'"

            let queryResult = try await featureTable.queryFeatures(using: queryParameters)
            let queryResultFeatures = Array(queryResult.features())

            if !queryResultFeatures.isEmpty {
                return GeometryEngine.combineExtents(
                    of: queryResultFeatures.compactMap(\.geometry)
                )
            } else {
                return nil
            }
        }

        /// Counts the number of features within the specified extent.
        /// - Parameter extent: The geometry defining the extent to query.
        /// - Returns: The count of features within the specified extent.
        /// - Throws: An error if the count operation fails.
        func countFeaturesWithinExtent(extent: Geometry) async throws -> Int {
            let queryParameters = QueryParameters()
            queryParameters.geometry = extent
            queryParameters.spatialRelationship = .intersects
            return try await featureLayer.featureTable!.queryFeatureCount(
                using: queryParameters
            )
        }
    }
}

private extension URL {
    /// The URL for the Medicare Hospital Spending layer service.
    static var medicareHospitalSpendLayer: URL {
        URL(string: "https://services1.arcgis.com/4yjifSiIG17X0gW4/arcgis/rest/services/Medicare_Hospital_Spending_per_Patient/FeatureServer/0")!
    }
}

#Preview {
    QueryFeatureCountAndExtentView()
}

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