Show grid

View on GitHub

Display coordinate system grids including Latitude/Longitude, MGRS, UTM and USNG on a map view. Also, toggle label visibility and change the color of grid lines and grid labels.

Image of Show grid

Use case

Grids are often used on printed maps, but can also be helpful on digital maps, to identify locations on a map.

How to use the sample

Tap on the Change Grid button in the toolbar to open a settings view. You can select type of grid from Grid Type (LatLong, MGRS, UTM and USNG) and modify its properties like label visibility, grid line color, and grid label color.

How it works

  1. Create an instance of one of the Grid types.
  2. Grid lines and labels can be styled per grid level with setLineSymbol(level, lineSymbol) and setTextSymbol(level, textSymbol) methods on the grid.
  3. The label position can be set with the labelPosition property on the grid.
  4. For the LatitudeLongitudeGrid type, you can specify a label format of decimal_degrees or degrees_minutes_seconds.
  5. To set the grid, use the grid property on the map view.

Relevant API

  • ArcGISMapView
  • Grid
  • LatitudeLongitudeGrid
  • MGRSGrid
  • SimpleLineSymbol
  • TextSymbol
  • USNGGrid
  • UTMGrid

Tags

coordinates, degrees, graticule, grid, latitude, longitude, MGRS, minutes, seconds, USNG, UTM

Sample Code

show_grid.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
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
//
// 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 'package:arcgis_maps/arcgis_maps.dart';
import 'package:flutter/material.dart';

import '../../utils/sample_state_support.dart';

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

  @override
  State<ShowGrid> createState() => _ShowGridState();
}

class _ShowGridState extends State<ShowGrid> with SampleStateSupport {
  // Create a controller for the map view.
  final _mapViewController = ArcGISMapView.createController();
  final _center = ArcGISPoint(
    x: -7702852.905619,
    y: 6217972.345771,
    spatialReference: SpatialReference.webMercator,
  );

  var _gridType = GridType.latitudeLongitude;
  var _gridColorType = GridColorType.red;
  var _gridLabelColorType = GridColorType.red;
  var _labelPositionType = GridLabelPositionType.allSides;
  var _labelFormatType = LatLongLabelFormatType.decimalDegrees;
  var _labelVisibility = true;

  @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,
                  ),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    ElevatedButton(
                      onPressed: _showGridOptions,
                      child: const Text('Change Grid'),
                    ),
                  ],
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  void onMapViewReady() {
    final map = ArcGISMap.withBasemapStyle(BasemapStyle.arcGISImagery);
    _mapViewController.arcGISMap = map;

    // Set the initial grid.
    _onGridChanged(_gridType);
    _onGridColorChanged(_gridColorType);
    _onLabelColorChanged(_gridLabelColorType);
    _onLabelPositionChanged(_labelPositionType);
    _onLabelVisibilityChanged(_labelVisibility);
  }

  // Change the grid based on the given value.
  void _onGridChanged(GridType gridType) {
    _gridType = gridType;

    final grid = gridType.value;
    _mapViewController.grid = grid;
    if (grid is LatitudeLongitudeGrid) {
      grid.labelFormat = LatitudeLongitudeGridLabelFormat.decimalDegrees;
      _mapViewController.setViewpointCenter(_center, scale: 23227.0);
    } else if (grid is UtmGrid) {
      _mapViewController.setViewpointCenter(_center, scale: 10000000.0);
    } else if (grid is UsngGrid || grid is MgrsGrid) {
      _mapViewController.setViewpointCenter(_center, scale: 23227.0);
    }
  }

  // Change the grid color based on the given value.
  void _onGridColorChanged(GridColorType colorType) {
    _gridColorType = colorType;
    if (_mapViewController.grid != null) {
      final grid = _mapViewController.grid!;
      for (int i = 0; i < grid.levelCount; i++) {
        final lineSymbol = SimpleLineSymbol(
          color: colorType.value,
          width: 1.0,
          style: SimpleLineSymbolStyle.solid,
        );
        grid.setLineSymbol(level: i, lineSymbol: lineSymbol);
      }
    }
  }

  // Change the label visibility based on the given value.
  void _onLabelVisibilityChanged(bool value) {
    _labelVisibility = value;
    if (_mapViewController.grid != null) {
      _mapViewController.grid!.labelVisibility = value;
    }
  }

  // Change the label color based on the given value.
  void _onLabelColorChanged(GridColorType colorType) {
    _gridLabelColorType = colorType;
    if (_mapViewController.grid != null) {
      final grid = _mapViewController.grid!;
      for (int i = 0; i < grid.levelCount; i++) {
        final textSymbol = TextSymbol(
          color: colorType.value,
          size: 14.0,
          horizontalAlignment: HorizontalAlignment.left,
          verticalAlignment: VerticalAlignment.bottom,
        )
          ..haloColor = Colors.black
          ..haloWidth = 5.0;
        grid.setTextSymbol(level: i, textSymbol: textSymbol);
      }
    }
  }

  // Change the label format if the grid is LatitudeLongitudeGrid.
  void _onLabelFormatChanged(LatLongLabelFormatType labelFormatType) {
    _labelFormatType = labelFormatType;
    if (_mapViewController.grid is LatitudeLongitudeGrid) {
      final grid = _mapViewController.grid! as LatitudeLongitudeGrid;
      grid.labelFormat = labelFormatType.value;
    }
  }

  // Change the label position based on the given value.
  void _onLabelPositionChanged(GridLabelPositionType labelPositionType) {
    _labelPositionType = labelPositionType;
    if (_mapViewController.grid != null) {
      final grid = _mapViewController.grid!;
      grid.labelPosition = labelPositionType.value;
    }
  }

  /// Show the grid options dialog.
  Future<void> _showGridOptions() async {
    return showDialog(
      context: context,
      barrierColor: Colors.transparent,
      builder: (context) {
        return Align(
          alignment: Alignment.bottomCenter,
          child: Material(
            child: Padding(
              padding: const EdgeInsets.all(10.0),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Row(
                    children: [
                      const Text('Grid Options'),
                      const Spacer(),
                      IconButton(
                        onPressed: () {
                          Navigator.of(context).pop();
                        },
                        icon: const Icon(Icons.close),
                      ),
                    ],
                  ),
                  GridOptions(
                    grids: MapViewGrids(
                      gridType: _gridType,
                      gridColorType: _gridColorType,
                      labelColorType: _gridLabelColorType,
                      labelPositionType: _labelPositionType,
                      labelFormatType: _labelFormatType,
                      labelVisible: _labelVisibility,
                    ),
                    onGridChanged: _onGridChanged,
                    onGridColorChanged: _onGridColorChanged,
                    onLabelColorChanged: _onLabelColorChanged,
                    onLabelPositionChanged: _onLabelPositionChanged,
                    onLabelFormatChanged: _onLabelFormatChanged,
                    onLabelVisibilityChanged: _onLabelVisibilityChanged,
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }
}

///
/// A widget that displays grid options.
///
class GridOptions extends StatefulWidget {
  final Function(GridType) onGridChanged;
  final Function(GridColorType) onGridColorChanged;
  final Function(GridColorType) onLabelColorChanged;
  final Function(GridLabelPositionType) onLabelPositionChanged;
  final Function(LatLongLabelFormatType) onLabelFormatChanged;
  final Function(bool) onLabelVisibilityChanged;
  final MapViewGrids grids;

  const GridOptions({
    super.key,
    required this.grids,
    required this.onGridChanged,
    required this.onGridColorChanged,
    required this.onLabelColorChanged,
    required this.onLabelPositionChanged,
    required this.onLabelFormatChanged,
    required this.onLabelVisibilityChanged,
  });

  @override
  State<GridOptions> createState() => _GridOptionsState();
}

class _GridOptionsState extends State<GridOptions> with SampleStateSupport {
  // Stateful variables.
  late GridType gridType;
  late GridColorType gridColorType;
  late GridColorType gridLabelColorType;
  late GridLabelPositionType labelPositionType;
  late LatLongLabelFormatType labelFormatType;

  late bool labelVisible;
  late bool isLabelFormatVisible;

  @override
  void initState() {
    super.initState();
    gridType = widget.grids.gridType;
    gridColorType = widget.grids.gridColorType;
    gridLabelColorType = widget.grids.labelColorType;
    labelPositionType = widget.grids.labelPositionType;
    labelFormatType = widget.grids.labelFormatType;
    labelVisible = widget.grids.labelVisible;
    isLabelFormatVisible = _shouldShowLabelFormat(gridType);
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: ListBody(
        children: [
          _buildGridDropdown(),
          isLabelFormatVisible
              ? _buildLatLongLabelFormatDropdown()
              : Container(),
          _buildGridColorDropdown(),
          _buildLabelColorDropdown(),
          _buildLabelPositionDropdown(),
          _buildLabelVisibilityCheckbox(),
        ],
      ),
    );
  }

  // Create a DropdownButtonFormField widget.
  static DropdownButtonFormField _createDropdownButtonFormField<T>({
    required T value,
    required String labelText,
    required List<T> items,
    required Function onChanged,
  }) {
    return DropdownButtonFormField(
      value: value,
      onChanged: (newValue) {
        onChanged(newValue!);
      },
      decoration: InputDecoration(
        labelText: labelText,
      ),
      items: items.map((value) {
        return DropdownMenuItem(
          value: value,
          child: Text(value.toString()),
        );
      }).toList(),
    );
  }

  DropdownButtonFormField _buildGridDropdown() {
    return _createDropdownButtonFormField(
      value: gridType,
      labelText: 'Grid Type',
      items: GridType.values,
      onChanged: (newGrid) {
        _changeGrid(newGrid);
        setState(() {
          gridType = newGrid;
          isLabelFormatVisible = _shouldShowLabelFormat(newGrid);
        });
      },
    );
  }

  DropdownButtonFormField _buildLatLongLabelFormatDropdown() {
    final formField = _createDropdownButtonFormField(
      value: labelFormatType,
      labelText: 'Label Format',
      items: LatLongLabelFormatType.values,
      onChanged: (newFormat) {
        widget.onLabelFormatChanged(newFormat);
        setState(() => labelFormatType = newFormat);
      },
    );
    return formField;
  }

  DropdownButtonFormField _buildGridColorDropdown() {
    return _createDropdownButtonFormField(
      value: gridColorType,
      labelText: 'Grid Color',
      items: GridColorType.values,
      onChanged: (newColor) {
        widget.onGridColorChanged(newColor);
        setState(() => gridColorType = newColor);
      },
    );
  }

  DropdownButtonFormField _buildLabelColorDropdown() {
    return _createDropdownButtonFormField(
      value: gridLabelColorType,
      labelText: 'Label Color',
      items: GridColorType.values,
      onChanged: (newColor) {
        widget.onLabelColorChanged(newColor!);
        setState(() => gridLabelColorType = newColor);
      },
    );
  }

  DropdownButtonFormField _buildLabelPositionDropdown() {
    return _createDropdownButtonFormField(
      value: labelPositionType,
      labelText: 'Label Position',
      items: GridLabelPositionType.values,
      onChanged: (newLabelPosition) {
        widget.onLabelPositionChanged(newLabelPosition);
        setState(() => labelPositionType = newLabelPosition);
      },
    );
  }

  Widget _buildLabelVisibilityCheckbox() {
    return Center(
      child: CheckboxListTile(
        title: const Text('Label Visible'),
        value: labelVisible,
        onChanged: (newVisible) {
          widget.onLabelVisibilityChanged(newVisible!);
          setState(() => labelVisible = newVisible);
        },
      ),
    );
  }

  // Change the Grid and apply the current settings.
  void _changeGrid(GridType gridType) {
    widget.onGridChanged(gridType);
    widget.onLabelFormatChanged(labelFormatType);
    widget.onGridColorChanged(gridColorType);
    widget.onLabelColorChanged(gridLabelColorType);
    widget.onLabelPositionChanged(labelPositionType);
    widget.onLabelVisibilityChanged(labelVisible);
  }

  // Set the visibility of the label format dropdown based on the grid type.
  bool _shouldShowLabelFormat(GridType grid) =>
      grid == GridType.latitudeLongitude;
}

//
// A data class that holds the grid options.
//
class MapViewGrids {
  final GridType gridType;
  final GridColorType gridColorType;
  final GridColorType labelColorType;
  final GridLabelPositionType labelPositionType;
  final LatLongLabelFormatType labelFormatType;
  final bool labelVisible;
  MapViewGrids({
    required this.gridType,
    required this.gridColorType,
    required this.labelColorType,
    required this.labelPositionType,
    required this.labelFormatType,
    required this.labelVisible,
  });
}

// An enum of grid label positions.
enum GridLabelPositionType {
  allSides('AllSides', GridLabelPosition.allSides),
  center('Center', GridLabelPosition.center),
  bottomLeft('BottomLeft', GridLabelPosition.bottomLeft),
  bottomRight('BottomRight', GridLabelPosition.bottomRight),
  topLeft('TopLeft', GridLabelPosition.topLeft),
  topRight('TopRight', GridLabelPosition.topRight),
  geographic('Geographic', GridLabelPosition.geographic);

  final String name;
  final GridLabelPosition value;
  const GridLabelPositionType(this.name, this.value);
  @override
  String toString() => name;
}

// An enum of grid colors.
enum GridColorType {
  red('Red', Colors.red),
  blue('Blue', Colors.blue),
  green('Green', Colors.green),
  yellow('Yellow', Colors.yellow);

  final String name;
  final Color value;
  const GridColorType(this.name, this.value);
  @override
  String toString() => name;
}

// An enum of label format types.
enum LatLongLabelFormatType {
  decimalDegrees(
    'Decimal Degrees',
    LatitudeLongitudeGridLabelFormat.decimalDegrees,
  ),
  degreesMinutesSeconds(
    'Degrees Minutes Seconds',
    LatitudeLongitudeGridLabelFormat.degreesMinutesSeconds,
  );

  final String name;
  final LatitudeLongitudeGridLabelFormat value;
  const LatLongLabelFormatType(this.name, this.value);
  @override
  String toString() => name;
}

// An enum of grid types.
enum GridType {
  latitudeLongitude('Latitude & Longitude'),
  mgrs('MGRS'),
  utm('UTM'),
  usng('USNG');

  final String name;
  Grid get value {
    switch (this) {
      case GridType.latitudeLongitude:
        return LatitudeLongitudeGrid();
      case GridType.mgrs:
        return MgrsGrid();
      case GridType.utm:
        return UtmGrid();
      case GridType.usng:
        return UsngGrid();
    }
  }

  const GridType(this.name);
  @override
  String toString() => name;
}

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