Query a map image sublayer

View on GitHubSample viewer app

Find features in a sublayer based on attributes and location.

Query a map image sublayer sample

Use case

Sublayers of an AGSArcGISMapImageLayer may expose an AGSFeatureTable. This allows you to perform the same queries available when working with a table from an AGSFeatureLayer attribute query, spatial query, statistics query, query for related features, etc. An image layer with a sublayer of counties can be queried by population to only show those above a minimum population.

How to use the sample

Specify a minimum population in the input field (values under 1810000 will produce a selection in all layers) and tap the "Query" button to query the sublayers in the current view extent. After a short time, the results for each sublayer will appear as graphics.

How it works

  1. Create an AGSArcGISMapImageLayer object using the URL of an image service.
  2. After loading the layer, get the sublayer you want to query with from the map image layer's mapImageSublayers array.
  3. Load the sublayer, and then get its AGSFeatureTable.
  4. Create AGSQueryParameters and define its whereClause and geometry.
  5. Use AGSFeatureTable.queryFeatures(with:completion:) to get an AGSFeatureQueryResult with features matching the query. The result is an enumerator of features.

Relevant API

  • AGSArcGISMapImageLayer
  • AGSArcGISMapImageSublayer
  • AGSFeatureTable
  • AGSQueryParameters

About the data

The AGSArcGISMapImageLayer in the map uses the "USA" map service as its data source. This service is hosted by ArcGIS Online, and is composed of four sublayers: "states", "counties", "cities", and "highways". Since the cities, counties, and states tables all have a POP2000 field, they can all execute a query against that attribute and a map extent.

Tags

search and query

Sample Code

QueryMapImageSublayerViewController.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
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
//
// Copyright © 2018 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 QueryMapImageSublayerViewController: UIViewController {
    /// The map displayed in the map view.
    let map: AGSMap
    let graphicsOverlay: AGSGraphicsOverlay

    required init?(coder: NSCoder) {
        map = AGSMap(basemapStyle: .arcGISStreets)

        /// The url of a map service containing sample data of the United States.
        let unitedStatesMapServiceURL = URL(string: "https://sampleserver6.arcgisonline.com/arcgis/rest/services/USA/MapServer")!
        // Create an image layer and add it to the map.
        let mapImageLayer = AGSArcGISMapImageLayer(url: unitedStatesMapServiceURL)
        map.operationalLayers.add(mapImageLayer)

        // Create the graphics overlay.
        graphicsOverlay = AGSGraphicsOverlay()

        super.init(coder: coder)

        // Begin loading the image layer.
        mapImageLayer.load { [weak self, unowned layer = mapImageLayer] (error) in
            if let error = error {
                self?.mapImageLayer(layer, didFailToLoadWith: error)
            } else {
                self?.mapImageLayerDidLoad(layer)
            }
        }
    }

    /// The map view managed by the view controller.
    @IBOutlet weak var mapView: AGSMapView!
    @IBOutlet weak var populationTextField: UITextField!
    @IBOutlet weak var queryButton: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()

        (self.navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["QueryMapImageSublayerViewController"]

        // Assign the map to the map view.
        mapView.map = map
        // Set the viewpoint.
        let center = AGSPoint(x: -12716000.00, y: 4170400.00, spatialReference: .webMercator())
        mapView.setViewpoint(AGSViewpoint(center: center, scale: 6000000))

        // Add the graphics overlay to the map view.
        mapView.graphicsOverlays.add(graphicsOverlay)

        enableControlsIfNeeded()
    }

    enum SublayerKey: Int, CaseIterable {
        case cities = 0
        case states = 2
        case counties = 3
    }

    /// The sublayers of the map image layer.
    var mapImageLayerSublayers = [SublayerKey: AGSArcGISMapImageSublayer]()

    /// Called in response to the map image layer loading successfully.
    func mapImageLayerDidLoad(_ layer: AGSArcGISMapImageLayer) {
        for key in SublayerKey.allCases {
            guard let sublayer = layer.mapImageSublayers[key.rawValue] as? AGSArcGISMapImageSublayer else { continue }
            mapImageLayerSublayers[key] = sublayer
            sublayer.load { [weak self] (error) in
                if let error = error {
                    print("Error loading sublayer \(sublayer.name): \(error)")
                } else {
                    self?.enableControlsIfNeeded()
                }
            }
        }
    }

    /// Called in response to the map image layer failing to load. Presents an
    /// alert announcing the failure.
    ///
    /// - Parameter error: The error that caused loading to fail.
    func mapImageLayer(_ layer: AGSArcGISMapImageLayer, didFailToLoadWith error: Error) {
        presentAlert(message: "Failed to load ArcGIS map image layer \(layer.name).")
    }

    /// Enables the text field and button if they can be enabled and haven't
    /// been already.
    func enableControlsIfNeeded() {
        guard isViewLoaded,
            !populationTextField.isEnabled,
            mapImageLayerSublayers.contains(where: { $0.value.loadStatus == .loaded }) else {
                return
        }
        populationTextField.isEnabled = true
        populationTextField.becomeFirstResponder()
        queryButton.isEnabled = true
    }

    /// The number formatter used to convert the user input string to a number.
    let numberFormatter = NumberFormatter()

    @IBAction func query(_ sender: Any) {
        populationTextField.resignFirstResponder()
        let trimmedText = populationTextField.text?.trimmingCharacters(in: .whitespaces) ?? ""
        if let value = numberFormatter.number(from: trimmedText) {
            populationValue = value.intValue
        } else if trimmedText.isEmpty {
            populationValue = nil
        } else {
            presentAlert(message: "The population value must be numeric.")
        }
    }

    /// The population value provided by the user.
    var populationValue: Int? {
        didSet {
            populationValueDidChange()
        }
    }

    /// Called in response to the population value changing.
    func populationValueDidChange() {
        graphicsOverlay.graphics.removeAllObjects()

        guard let populationValue = populationValue else { return }

        let populationQuery = AGSQueryParameters()
        populationQuery.whereClause = "POP2000 > \(populationValue)"
        populationQuery.geometry = mapView.currentViewpoint(with: .boundingGeometry)?.targetGeometry

        for (_, sublayer) in mapImageLayerSublayers {
            guard let table = sublayer.table else { continue }
            table.queryFeatures(with: populationQuery) { [weak self] (result, error) in
                if let result = result {
                    self?.featureTable(table, featureQueryDidSucceedWith: result)
                } else if let error = error {
                    self?.featureTable(table, featureQueryDidFailWith: error)
                }
            }
        }
    }

    /// Called when a feature query of a feature table finishes successfully.
    ///
    /// - Parameters:
    ///   - featureTable: The feature table that was queried.
    ///   - result: The feature query result.
    func featureTable(_ featureTable: AGSFeatureTable, featureQueryDidSucceedWith result: AGSFeatureQueryResult) {
        let symbol = makeSymbol(featureTable: featureTable)
        let graphics: [AGSGraphic] = result.featureEnumerator().map {
            AGSGraphic(geometry: ($0 as! AGSFeature).geometry, symbol: symbol, attributes: nil)
        }
        graphicsOverlay.graphics.addObjects(from: graphics)
    }

    /// Called when a feature query of a feature table is unsuccessful.
    ///
    /// - Parameters:
    ///   - featureTable: The feature table that was queried.
    ///   - error: The error that caused the query to fail.
    func featureTable(_ featureTable: AGSFeatureTable, featureQueryDidFailWith error: Error) {
        print("\(featureTable.tableName) feature query failed: \(error)")
    }

    /// Creates a symbol for features of the given feature table.
    ///
    /// - Parameter featureTable: A feature table.
    /// - Returns: An `AGSSymbol` object.
    func makeSymbol(featureTable: AGSFeatureTable) -> AGSSymbol? {
        switch featureTable {
        case mapImageLayerSublayers[.cities]?.table:
            return AGSSimpleMarkerSymbol(style: .circle, color: .red, size: 16)
        case mapImageLayerSublayers[.states]?.table:
            let outline = AGSSimpleLineSymbol(style: .solid, color: #colorLiteral(red: 0, green: 0.5450980392, blue: 0.5450980392, alpha: 1), width: 6)
            return AGSSimpleFillSymbol(style: .null, color: .cyan, outline: outline)
        case mapImageLayerSublayers[.counties]?.table:
            let outline = AGSSimpleLineSymbol(style: .dash, color: .cyan, width: 2)
            return AGSSimpleFillSymbol(style: .diagonalCross, color: .cyan, outline: outline)
        default:
            return nil
        }
    }
}

extension QueryMapImageSublayerViewController: UITextFieldDelegate {
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        query(textField)
        return false
    }
}

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