Control annotation sublayer visibility

View on GitHub

Use annotation sublayers to gain finer control of annotation layer subtypes.

Image of control annotation sublayer visibility

Use case

Annotation, which differs from labels by having a fixed place and size, is typically only relevant at particular scales. Annotation sublayers allow for finer control of annotation by allowing properties (like visibility in the map and legend) to be set and others to be read (like name) on subtypes of an annotation layer.

An annotation dataset which marks valves as "Opened" or "Closed", might be set to display the "Closed" valves over a broader range of scales than the "Opened" valves, if the "Closed" data is considered more relevant by the map's author. Regardless, the user can be given a manual option to set visibility of annotation sublayers on and off, if required.

How to use the sample

Start the sample and take note of the visibility of the annotation. Zoom in and out to see the annotation turn on and off based on scale ranges set on the data.

Use the switches to manually set "Open" and "Closed" annotation sublayers visibility to on or off.

How it works

  1. Load a MobileMapPackage that contains AnnotationSublayer.
  2. Get the sublayers from the map package's layers by calling Sublayer.subLayerContents.
  3. You can toggle the visibility of each sublayer manually using Sublayer.isVisible property.
  4. To determine if a sublayer is visible at the current scale of the ArcGISMapView, use Sublayer.isVisibleAtScale(ArcGISMapViewController.scale), by passing in the map's current scale.

Relevant API

  • AnnotationLayer
  • AnnotationSublayer
  • LayerContent

Offline data

This sample uses Gas Device Anno Mobile Map Package. It is downloaded from ArcGIS Online as part of the sample.

About the data

The scale ranges were set by the map's author using ArcGIS Pro:

  • The "Open" annotation sublayer has its maximum scale set to 1:500 and its minimum scale set to 1:2000.
  • The "Closed" annotation sublayer has no minimum or maximum scales set, so will be drawn at all scales.

Tags

annotation, scale, text, utilities, visualization

Sample Code

control_annotation_sublayer_visibility.dart
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
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
// 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 'dart:io';
import 'dart:math';

import 'package:arcgis_maps/arcgis_maps.dart';
import 'package:arcgis_maps_sdk_flutter_samples/utils/sample_data.dart';
import 'package:arcgis_maps_sdk_flutter_samples/utils/sample_state_support.dart';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';

class ControlAnnotationSublayerVisibility extends StatefulWidget {
  const ControlAnnotationSublayerVisibility({super.key});

  @override
  State<ControlAnnotationSublayerVisibility> createState() =>
      _ControlAnnotationSublayerVisibilityState();
}

class _ControlAnnotationSublayerVisibilityState
    extends State<ControlAnnotationSublayerVisibility> with SampleStateSupport {
  // Create a controller for the map view.
  final _mapViewController = ArcGISMapView.createController();

  // Declare labels text.
  var _openLabel = '';
  var _closedLabel = '';
  var _currentScaleLabel = '';

  // Declare open label color.
  Color? _openLabelColor;

  // Declare the annotation sub layers.
  late final AnnotationSublayer _closedSublayer;
  late final AnnotationSublayer _openSublayer;

  // A flag for when the map view is ready and controls can be used.
  var _ready = false;

  // A flag for when the settings bottom sheet is visible.
  var _settingsVisible = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        top: false,
        child: Stack(
          children: [
            Column(
              children: [
                Expanded(
                  // Add a map view to the widget tree and set a controller.
                  child: ArcGISMapView(
                    controllerProvider: () => _mapViewController,
                    onMapViewReady: onMapViewReady,
                  ),
                ),
                // A button to control Settings bottom sheet.
                Center(
                  child: ElevatedButton(
                    onPressed: () => setState(() => _settingsVisible = true),
                    child: const Text('Settings'),
                  ),
                ),
              ],
            ),
            // Display a progress indicator and prevent interaction until state is ready.
            Visibility(
              visible: !_ready,
              child: const SizedBox.expand(
                child: ColoredBox(
                  color: Colors.white30,
                  child: Center(child: CircularProgressIndicator()),
                ),
              ),
            ),
          ],
        ),
      ),
      bottomSheet: _settingsVisible ? buildSettings(context) : null,
    );
  }

  // The build method for the Settings bottom sheet.
  Widget buildSettings(BuildContext context) {
    return Container(
      padding: EdgeInsets.fromLTRB(
        20.0,
        20.0,
        20.0,
        max(
          20.0,
          View.of(context).viewPadding.bottom /
              View.of(context).devicePixelRatio,
        ),
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Row(
            children: [
              Text(
                'Settings',
                style: Theme.of(context).textTheme.titleLarge,
              ),
              const Spacer(),
              IconButton(
                icon: const Icon(Icons.close),
                onPressed: () => setState(() => _settingsVisible = false),
              ),
            ],
          ),
          Row(
            children: [
              Text(
                _openLabel,
                style: TextStyle(color: _openLabelColor),
              ),
              const Spacer(),
              Switch(
                value: _openSublayer.isVisible,
                onChanged: (value) {
                  // Set the visibility of the open sub layer.
                  setState(() => _openSublayer.isVisible = value);
                },
              ),
            ],
          ),
          Row(
            children: [
              Text(
                _closedLabel,
              ),
              const Spacer(),
              Switch(
                value: _closedSublayer.isVisible,
                onChanged: (value) {
                  // Set the visibility of the closed sub layer.
                  setState(() => _closedSublayer.isVisible = value);
                },
              ),
            ],
          ),
          Text(
            _currentScaleLabel,
          ),
        ],
      ),
    );
  }

  void onMapViewReady() async {
    try {
      await downloadSampleData(['b87307dcfb26411eb2e92e1627cb615b']);
      final appDir = await getApplicationDocumentsDirectory();

      // Load the mobile map package.
      final mmpkFile = File('${appDir.absolute.path}/GasDeviceAnno.mmpk');
      // Mobile map package that contains annotation layers.
      final mmpk = MobileMapPackage.withFileUri(mmpkFile.uri);
      await mmpk.load();

      // Get the first map in the mobile map package and set to the map view.
      _mapViewController.arcGISMap = mmpk.maps.first;

      // Get the annotation layer from the MapView operational layers.
      final annotationLayer = _mapViewController.arcGISMap!.operationalLayers
          .whereType<AnnotationLayer>()
          .first;

      // Load the annotation layer.
      await annotationLayer.load();

      setState(() {
        // Get the annotation sub layers.
        _closedSublayer =
            annotationLayer.subLayerContents[0] as AnnotationSublayer;

        _openSublayer =
            annotationLayer.subLayerContents[1] as AnnotationSublayer;

        // Set the closed label content.
        _closedLabel = _closedSublayer.name;

        // Set the open label content.
        _openLabel =
            '${_openSublayer.name} (1:${_openSublayer.maxScale.toInt()} - 1:${_openSublayer.minScale.toInt()})';
      });

      // Add event handler for changing the text color to indicate whether the "open" sublayer is visible at the current scale.
      _mapViewController.onViewpointChanged.listen((_) {
        // Check if the sublayer is visible at the current map scale.
        if (_openSublayer.isVisibleAtScale(_mapViewController.scale)) {
          setState(() => _openLabelColor = Colors.purple);
        } else {
          setState(() => _openLabelColor = null);
        }
        // Set the current map scale text.
        setState(
          () => _currentScaleLabel =
              'Current map scale: 1:${_mapViewController.scale.toInt()}',
        );
      });

      // Set the ready state variable to true to enable the sample UI.
      setState(() => _ready = true);
    } on ArcGISException catch (e) {
      showMessageDialog('${e.message}.');
    } on Exception {
      showMessageDialog(
        'There was an error loading the data required for the sample.',
      );
    }
  }

  void showMessageDialog(String message) {
    // Show a dialog with the provided message.
    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          content: Text(message),
        );
      },
    );
  }
}

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