Create symbol styles from web styles

View on GitHub
Sample viewer app

Create symbol styles from a style file hosted on a portal.

Image of create symbol styles from web styles

Use case

Style files hosted on an ArcGIS Online or Enterprise portal are known as web styles. They can be used to style symbols on a feature layer or graphic overlay. Since styles are published from ArcGIS Pro, you can author and design your own beautiful multilayer vector symbols. These vector symbols look good at any resolution and scale well. Runtime users can now access these styles from their native application, and make use of the vector symbols within them to enhance features and graphics in the map.

How to use the sample

The sample displays a map with a set of symbols that represent the categories of the features within the dataset. Pan and zoom on the map and view the legend to explore the appearance and names of the different symbols from the selected symbol style.

How it works

  1. Create an AGSFeatureLayer and add it to the map.
  2. Create an AGSUniqueValueRenderer and set it to the feature layer.
  3. Create an AGSSymbolStyle from a portal by passing in the web style name and portal.
  4. Search for symbols in the symbol style by name using AGSSymbolStyle.symbol(forKeys:completion:) method.
  5. Create an AGSSymbol from the search result.
  6. Create AGSUniqueValue objects for each symbol with defined category values to map the symbol to features on the feature layer.
  7. Add each AGSUniqueValue to the AGSUniqueValueRenderer.

Relevant API

  • AGSFeatureLayer
  • AGSSymbol
  • AGSSymbolStyle
  • AGSUniqueValue
  • AGSUniqueValueRenderer

About the data

The sample uses the 'Esri2DPointSymbolsStyle' Web Style.

The map shows features from the LA County Points of Interest service hosted on ArcGIS Online.

Additional information

2D web styles, dictionary web styles, and 3D web styles can all be hosted on an ArcGIS Online or Enterprise portal.

Tags

renderer, symbol, symbology, web style

Sample Code

CreateSymbolStylesFromWebStylesViewController.swift
                                                                                                                                                                                                                                                                                 
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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
// Copyright 2021 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 CreateSymbolStylesFromWebStylesViewController: UIViewController, UIAdaptivePresentationControllerDelegate {
    // MARK: Storyboard views

    /// The map view managed by the view controller.
    @IBOutlet var mapView: AGSMapView! {
        didSet {
            mapView.map = makeMap(referenceScale: 1e5)
            mapView.setViewpoint(
                AGSViewpoint(
                    latitude: 34.28301,
                    longitude: -118.44186,
                    scale: 1e4
                )
            )
        }
    }
    /// The button to show legend table.
    @IBOutlet var legendBarButtonItem: UIBarButtonItem!

    // MARK: Instance properties

    /// The Esri 2D point symbol style created from a web style.
    let symbolStyle = AGSSymbolStyle(styleName: "Esri2DPointSymbolsStyle", portal: .arcGISOnline(withLoginRequired: false))
    /// The observation on the map view's `mapScale` property.
    var mapScaleObservation: NSKeyValueObservation?
    /// The data source for the legend table.
    private var symbolsDataSource: SymbolsDataSource? {
        didSet {
            legendBarButtonItem.isEnabled = true
        }
    }

    /// A feature layer with LA County Points of Interest service.
    let featureLayer: AGSFeatureLayer = {
        let serviceFeatureTable = AGSServiceFeatureTable(url: URL(string: "http://services.arcgis.com/V6ZHFr6zdgNZuVG0/arcgis/rest/services/LA_County_Points_of_Interest/FeatureServer/0")!)
        let layer = AGSFeatureLayer(featureTable: serviceFeatureTable)
        return layer
    }()

    // MARK: Methods

    /// Create a map with a reference scale.
    func makeMap(referenceScale: Double) -> AGSMap {
        let map = AGSMap(basemapStyle: .arcGISLightGray)
        map.referenceScale = referenceScale
        return map
    }

    /// Create an `AGSUniqueValueRenderer` to render feature layer with symbol styles.
    /// - Parameters:
    ///   - fieldNames: The attributes to match the unique values against.
    ///   - symbolDetails: A dictionary of symbols and their associated information.
    /// - Returns: An `AGSUniqueValueRenderer` object.
    func makeUniqueValueRenderer(fieldNames: [String], symbolDetails: [AGSSymbol: (name: String, values: [String])]) -> AGSUniqueValueRenderer {
        let renderer = AGSUniqueValueRenderer()
        renderer.fieldNames = fieldNames
        renderer.uniqueValues = symbolDetails.flatMap { symbol, infos in
            // For each category value of a symbol, we need to create a
            // unique value for it, so the field name matches to all
            // category values.
            infos.values.map { symbolValue in
                AGSUniqueValue(description: "", label: infos.name, symbol: symbol, values: [symbolValue])
            }
        }
        return renderer
    }

    /// Get certain types of symbols from a symbol style.
    /// - Parameters:
    ///   - symbolStyle: An `AGSSymbolStyle` object.
    ///   - types: The types of symbols to search in the symbol style.
    private func getSymbols(symbolStyle: AGSSymbolStyle, types: [SymbolType]) {
        let getSymbolsGroup = DispatchGroup()
        var legendItems = [LegendItem]()
        var symbolDetails = [AGSSymbol: (String, [String])]()

        // Get the `AGSSymbol` for each symbol type.
        types.forEach { category in
            getSymbolsGroup.enter()
            let symbolName = category.symbolName
            let symbolCategoryValues = category.symbolCategoryValues
            symbolStyle.symbol(forKeys: [symbolName]) { symbol, _ in
                // Add the symbol to result dictionary and ignore any error.
                if let symbol = symbol {
                    symbolDetails[symbol] = (symbolName, symbolCategoryValues)
                    // Get the image swatch for the symbol.
                    symbol.createSwatch { image, _ in
                        defer { getSymbolsGroup.leave() }
                        guard let image = image else { return }
                        legendItems.append(LegendItem(name: symbolName, image: image))
                    }
                } else {
                    getSymbolsGroup.leave()
                }
            }
        }

        getSymbolsGroup.notify(queue: .main) { [weak self] in
            guard let self = self else { return }
            // Create the data source for the legend table.
            self.symbolsDataSource = SymbolsDataSource(legendItems: legendItems.sorted { $0.name < $1.name })
            // Create unique values and set them to the renderer.
            self.featureLayer.renderer = self.makeUniqueValueRenderer(fieldNames: ["cat2"], symbolDetails: symbolDetails)
            // Add the feature layer to the map.
            self.mapView.map?.operationalLayers.add(self.featureLayer)
        }
    }

    // MARK: UIViewController

    override func viewDidLoad() {
        super.viewDidLoad()
        // Add the source code button item to the right of navigation bar.
        (navigationItem.rightBarButtonItem as? SourceCodeBarButtonItem)?.filenames = ["CreateSymbolStylesFromWebStylesViewController"]
        // Get the symbols from the symbol style hosted on an ArcGIS portal.
        getSymbols(symbolStyle: symbolStyle, types: SymbolType.allCases)
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        mapScaleObservation = mapView.observe(\.mapScale, options: .initial) { [weak self] (_, _) in
            DispatchQueue.main.async {
                guard let self = self else { return }
                self.featureLayer.scaleSymbols = self.mapView.mapScale >= 8e4
            }
        }
    }

    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        mapScaleObservation = nil
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "LegendTableSegue",
           let controller = segue.destination as? UITableViewController {
            controller.presentationController?.delegate = self
            controller.tableView.dataSource = symbolsDataSource
        }
    }

    // MARK: UIAdaptivePresentationControllerDelegate

    func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
        // Ensure that the settings are shown in a popover on small displays.
        return .none
    }
}

// MARK: - SymbolsDataSource, UITableViewDataSource

private class SymbolsDataSource: NSObject, UITableViewDataSource {
    /// The legend items for the legend table.
    private let legendItems: [LegendItem]

    init(legendItems: [LegendItem]) {
        self.legendItems = legendItems
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        legendItems.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Basic", for: indexPath)
        let legendItem = legendItems[indexPath.row]
        cell.textLabel?.text = legendItem.name
        cell.imageView?.image = legendItem.image
        return cell
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        1
    }

    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        "Symbol Styles"
    }
}

// MARK: - LegendItem

private struct LegendItem {
    let name: String
    let image: UIImage
}

// MARK: - SymbolType

private enum SymbolType: CaseIterable, Comparable {
    case atm, beach, campground, cityHall, hospital, library, park, placeOfWorship, policeStation, postOffice, school, trail

    /// The names of the symbols in the web style.
    var symbolName: String {
        let name: String
        switch self {
        case .atm:
            name = "atm"
        case .beach:
            name = "beach"
        case .campground:
            name = "campground"
        case .cityHall:
            name = "city-hall"
        case .hospital:
            name = "hospital"
        case .library:
            name = "library"
        case .park:
            name = "park"
        case .placeOfWorship:
            name = "place-of-worship"
        case .policeStation:
            name = "police-station"
        case .postOffice:
            name = "post-office"
        case .school:
            name = "school"
        case .trail:
            name = "trail"
        }
        return name
    }

    /// The category names of features represented by a type of symbol.
    var symbolCategoryValues: [String] {
        let values: [String]
        switch self {
        case .atm:
            values = ["Banking and Finance"]
        case .beach:
            values = ["Beaches and Marinas"]
        case .campground:
            values = ["Campgrounds"]
        case .cityHall:
            values = ["City Halls", "Government Offices"]
        case .hospital:
            values = ["Hospitals and Medical Centers", "Health Screening and Testing", "Health Centers", "Mental Health Centers"]
        case .library:
            values = ["Libraries"]
        case .park:
            values = ["Parks and Gardens"]
        case .placeOfWorship:
            values = ["Churches"]
        case .policeStation:
            values = ["Sheriff and Police Stations"]
        case .postOffice:
            values = ["DHL Locations", "Federal Express Locations"]
        case .school:
            values = ["Public High Schools", "Public Elementary Schools", "Private and Charter Schools"]
        case .trail:
            values = ["Trails"]
        }
        return values
    }
}

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