Show labels on layer

View on GitHub

Display custom labels on a feature layer.

Image of show labels on layer

Use case

Labeling features is useful to visually display a key piece of information or attribute of a feature on a map. For example, you may want to label rivers or street with their names.

How to use the sample

Pan and zoom around the United States. Labels for congressional districts will be shown in red for Republican districts and blue for Democrat districts. Notice how labels pop into view as you zoom in.

How it works

  1. Create a ServiceFeatureTable using a feature service URL.
  2. Create a FeatureLayer from the service feature table.
  3. Create a TextSymbol to use for displaying the label text.
  4. Create an ArcadeLabelExpression for the label definition.
    • You can use fields of the feature by using $feature.field_name in the expression.
  5. Create a new LabelDefinition from the arcade label expression and text symbol.
  6. Add the definition to the feature layer with featureLayer.addLabelDefinition(labelDefinition).
  7. Lastly, enable labels on the layer using featureLayer.labelsAreEnabled.

Relevant API

  • ArcadeLabelExpression
  • FeatureLayer
  • LabelDefinition
  • TextSymbol

About the data

This sample uses the USA 116th Congressional Districts feature layer hosted on ArcGIS Online.

Additional information

Help regarding the Arcade label expression script for defining a label definition can be found on the Esri Developer website.

Tags

arcade, attribute, deconfliction, label, labeling, string, symbol, text, visualization

Sample Code

ShowLabelsOnLayerView.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 2023 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 ShowLabelsOnLayerView: View {
    /// A map with a light gray canvas basemap centered on the USA.
    @State private var map: Map = {
        let map = Map(basemapStyle: .arcGISLightGrayBase)
        map.initialViewpoint = Viewpoint(
            center: Point(x: -10626699.4, y: 2150308.5),
            scale: 74016655.9
        )
        return map
    }()

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

    var body: some View {
        MapView(map: map)
            .task {
                do {
                    // Create a portal item from an id.
                    let portalItem = PortalItem(
                        portal: .arcGISOnline(connection: .anonymous),
                        id: .usaCongressionalDistricts
                    )

                    try await portalItem.load()

                    // Create a feature layer from the portal item.
                    let featureLayer = FeatureLayer(item: portalItem)

                    // Add the layer to the map.
                    map.addOperationalLayer(featureLayer)

                    // Add labels to the layer.
                    addLabels(to: featureLayer)
                } catch {
                    // Present an error if feature table fails to load.
                    self.error = error
                }
            }
            .errorAlert(presentingError: $error)
    }
}

private extension ShowLabelsOnLayerView {
    /// Adds labels to a feature layer.
    /// - Parameter layer: The `FeatureLayer` to add the labels to.
    func addLabels(to layer: FeatureLayer) {
        // Create label definitions for the two groups.
        let democratDefinition = makeLabelDefinition(party: "Democrat", color: .blue)
        let republicanDefinition = makeLabelDefinition(party: "Republican", color: .red)

        // Add the label definitions to the layer.
        layer.addLabelDefinitions([democratDefinition, republicanDefinition])

        // Turn on labeling.
        layer.labelsAreEnabled = true
    }

    /// Creates a label definition for the given PARTY field value and color.
    /// - Parameters:
    ///   - party: A `String` representing the party.
    ///   - color: The `UIColor` for the label.
    /// - Returns: A new `LabelDefinition` object.
    private func makeLabelDefinition(party: String, color: UIColor) -> LabelDefinition {
        // The styling for the label.
        let textSymbol = TextSymbol(color: color, size: 12)
        textSymbol.haloColor = .white
        textSymbol.haloWidth = 2

        // An SQL WHERE statement for filtering the features this label applies to.
        let whereStatement = "PARTY = '\(party)'"

        // An expression that specifies the content of the label using the table's attributes.
        let expression = "$feature.NAME + ' (' + left($feature.PARTY,1) + ')\\nDistrict' + $feature.CDFIPS"

        // Make an arcade label expression.
        let arcadeLabelExpression = ArcadeLabelExpression(arcadeString: expression)
        let labelDefinition = LabelDefinition(labelExpression: arcadeLabelExpression, textSymbol: textSymbol)
        labelDefinition.placement = .polygonAlwaysHorizontal
        labelDefinition.whereClause = whereStatement

        return labelDefinition
    }
}

private extension PortalItem.ID {
    /// An id for a USA Congressional Districts Analysis feature table.
    static var usaCongressionalDistricts: Self { Self("cc6a869374434bee9fefad45e291b779 ")! }
}

#Preview {
    ShowLabelsOnLayerView()
}

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