Download vector tiles to local cache

View on GitHub

Export tiles from an online vector tile service.

Image of download vector tiles to local cache

Use case

Field workers with limited network connectivity can use exported vector tiles as a basemap for use while offline.

How to use the sample

When the vector tiled layer loads, zoom in to the extent you want to export. The red box shows the extent that will be exported. Tap the "Download Vector Tiles" button to start the job. An error will show if the extent is larger than the maximum limit allowed. When finished, the downloaded vector tiles cache will be displayed in the map view.

How it works

  1. Create an ArcGISVectorTiledLayer from the map's base layers.
  2. Create an ExportVectorTilesTask using the vector tiled layer's URL.
  3. Create default ExportVectorTilesParameters from the task, specifying extent and maximum scale.
  4. Create an ExportVectorTilesJob from the task using the parameters, and specifying a vector tile cache path and an item resource path. The resource path is required if you want to export the tiles with the style.
  5. Start the job, and once it completes successfully, get the resulting ExportVectorTilesResult.
  6. Get the VectorTileCache and ItemResourceCache from the result to create an ArcGISVectorTiledLayer that can be displayed to the map view.

Relevant API

  • ArcGISVectorTiledLayer
  • ExportVectorTilesJob
  • ExportVectorTilesParameters
  • ExportVectorTilesResult
  • ExportVectorTilesTask
  • ItemResourceCache
  • VectorTileCache

Additional information

NOTE: Downloading Tiles for offline use requires authentication with the web map's server. To use this sample, you will require an ArcGIS Online account.

Vector tiles have high drawing performance and smaller file size compared to regular tiled layers, due to consisting solely of points, lines, and polygons. Learn more about the characteristics of ArcGIS vector tiled layers.

Tags

cache, download, offline, vector

Sample Code

download_vector_tiles_to_local_cache.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
//
// 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:async';
import 'dart:io';
import 'package:arcgis_maps/arcgis_maps.dart';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';

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

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

  @override
  State<DownloadVectorTilesToLocalCache> createState() =>
      _DownloadVectorTilesToLocalCacheState();
}

class _DownloadVectorTilesToLocalCacheState
    extends State<DownloadVectorTilesToLocalCache> with SampleStateSupport {
  // Create a controller for the map view.
  final _mapViewController = ArcGISMapView.createController();
  // A instance of the ExportVectorTilesJob.
  ExportVectorTilesJob? _exportVectorTilesJob;
  // A progress number for the download job.
  var _progress = 0.0;
  // A flag to indicate if the preview map is open.
  var _previewMap = false;
  // A flag to indicate if the download job has started.
  var _isJobStarted = false;
  // A flag for when the map view is ready and controls can be used.
  var _ready = false;
  // A key to access the map view widget.
  final _mapKey = GlobalKey();
  // A key to be used when converting screen locations to map coordinates.
  final _outlineKey = GlobalKey();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        top: false,
        child: Stack(
          children: [
            Column(
              children: [
                Expanded(
                  child: Stack(
                    children: [
                      // Add a map view to the widget tree and set a controller.
                      ArcGISMapView(
                        key: _mapKey,
                        controllerProvider: () => _mapViewController,
                        onMapViewReady: onMapViewReady,
                      ),
                      // Add a red outline that marks the region to be taken offline.
                      Visibility(
                        visible: !_previewMap,
                        child: buildRedOutline(),
                      ),
                    ],
                  ),
                ),
                Center(
                  child: _previewMap
                      ? ElevatedButton(
                          onPressed: closePreviewVectorTiles,
                          child: const Text('Close Preview Vector Tiles'),
                        )
                      : ElevatedButton(
                          onPressed:
                              _isJobStarted ? null : startDownloadVectorTiles,
                          child: const Text('Download Vector Tiles'),
                        ),
                ),
              ],
            ),
            // Display a progress indicator and prevent interaction until state is ready.
            Visibility(
              visible: !_ready,
              child: SizedBox.expand(
                child: Container(
                  color: Colors.white30,
                  child: const Center(
                    child: CircularProgressIndicator(),
                  ),
                ),
              ),
            ),
            // Display a progress indicator and a cancel button during the offline map generation.
            Visibility(
              visible: _isJobStarted,
              child: Center(
                child: buildProgressIndicator(),
              ),
            ),
          ],
        ),
      ),
    );
  }

  // the method to be called when the map view is ready
  void onMapViewReady() {
    // disable the map view's rotation.
    _mapViewController.interactionOptions.rotateEnabled = false;

    setupInitialMapView();
    // Set the ready state variable to true to enable the sample UI.
    setState(() => _ready = true);
  }

  // Set up the initial map view.
  void setupInitialMapView() {
    final map = ArcGISMap.withBasemapStyle(BasemapStyle.arcGISStreetsNight);
    _mapViewController.arcGISMap = map;
    _mapViewController.setViewpoint(
      Viewpoint.fromCenter(
        ArcGISPoint(
          x: -117.195800,
          y: 34.057386,
          spatialReference: SpatialReference.wgs84,
        ),
        scale: 100000,
      ),
    );
  }

  // After the tiles caches are previewed, reset the map into initial state.
  void closePreviewVectorTiles() {
    setupInitialMapView();
    setState(() => _previewMap = false);
    setState(() => _isJobStarted = false);
  }

  // Cancel the export vector tiles job.
  void cancelDownloadingJob() async {
    setState(() => _progress = 0.0);
    setState(() => _isJobStarted = false);

    // Cancel the export vector tiles job, the job status will be failed.
    // The status listener will popup a dialog to show the error message.
    await _exportVectorTilesJob?.cancel();
  }

  // Start to download the vector tiles for the outlined region.
  void startDownloadVectorTiles() async {
    // Get the download area.
    final downloadArea = downloadAreaEnvelope();
    // Get the ArcGISVectorTiledLayer which the vector tiles cache will be downloaded from.
    final layer = _mapViewController.arcGISMap?.basemap?.baseLayers.first;
    if (downloadArea == null ||
        layer == null ||
        layer is! ArcGISVectorTiledLayer ||
        layer.uri == null) {
      _showErrorDialog('Invalid download area or layer');
      return;
    }

    // Show the progress indicator to start the download process.
    setState(() => _isJobStarted = true);

    // Create an export vector tiles task.
    final vectorTilesExportTask = ExportVectorTilesTask.withUri(layer.uri!);
    await vectorTilesExportTask.load();

    // Get the cache directory to store the downloaded vector tiles
    final resourceDirectory = await _getDownloadDirectory();
    final vtpkFile = File(
      '$resourceDirectory${Platform.pathSeparator}myTileCacheDownload.vtpk',
    );

    // Create the default export vector tiles parameters,
    // and shrink the area of interest by 10%.
    final exportVectorTilesParameters =
        await vectorTilesExportTask.createDefaultExportVectorTilesParameters(
      areaOfInterest: downloadArea,
      maxScale: _mapViewController.scale * 0.1,
    );

    // Create the export vector tiles job.
    _exportVectorTilesJob =
        vectorTilesExportTask.exportVectorTilesWithItemResourceCache(
      parameters: exportVectorTilesParameters,
      vectorTileCacheUri: vtpkFile.uri,
      itemResourceCacheUri: Uri.directory(resourceDirectory),
    );

    // Listen to the job's progress.
    _exportVectorTilesJob?.onProgressChanged.listen(
      (progress) {
        setState(() => _progress = progress * 0.01);
      },
    );

    _exportVectorTilesJob?.onStatusChanged.listen(
      (status) {
        if (status == JobStatus.succeeded) {
          setState(() => _progress = 100.0);
          if (mounted) {
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(
                content: const Text('Downloaded vector tiles successfully'),
                duration: const Duration(seconds: 5),
                backgroundColor: Theme.of(context).colorScheme.secondary,
              ),
            );
          }
        }
      },
    );

    try {
      // Start the export vector tiles job.
      final result = await _exportVectorTilesJob?.run();

      // If the job succeeded, load the downloaded caches into the map view.
      _loadExportedVectorTiles(result);
    } on ArcGISException catch (e) {
      _showErrorDialog(e.message);
    } finally {
      _exportVectorTilesJob = null;
    }
    // Dismiss the progress indicator.
    setState(() => _isJobStarted = false);
  }

  // Show an error dialog.
  void _showErrorDialog(String message) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('Info', style: Theme.of(context).textTheme.titleMedium),
        content: Text(
          'Failed to download vector tiles:\n$message',
        ),
        actions: [
          TextButton(
            onPressed: () {
              Navigator.of(context).pop();
            },
            child: const Text('Close'),
          ),
        ],
      ),
    );
  }

  // Calculate the Envelope of the outlined region.
  Envelope? downloadAreaEnvelope() {
    final outlineContext = _outlineKey.currentContext;
    final mapContext = _mapKey.currentContext;
    if (outlineContext == null || mapContext == null) return null;

    // Get the global screen rect of the outlined region.
    final outlineRenderBox = outlineContext.findRenderObject() as RenderBox;
    final outlineGlobalScreenRect =
        outlineRenderBox.localToGlobal(Offset.zero) & outlineRenderBox.size;

    // Convert the global screen rect to a rect local to the map view.
    final mapRenderBox = mapContext.findRenderObject() as RenderBox;
    final mapLocalScreenRect =
        outlineGlobalScreenRect.shift(-mapRenderBox.localToGlobal(Offset.zero));

    // Convert the local screen rect to map coordinates.
    final locationTopLeft =
        _mapViewController.screenToLocation(screen: mapLocalScreenRect.topLeft);
    final locationBottomRight = _mapViewController.screenToLocation(
      screen: mapLocalScreenRect.bottomRight,
    );
    if (locationTopLeft == null || locationBottomRight == null) return null;

    // Create an Envelope from the map coordinates.
    return Envelope.fromPoints(locationTopLeft, locationBottomRight);
  }

  // Create a directory to store the downloaded vector tiles.
  Future<String> _getDownloadDirectory() async {
    final directory = await getApplicationDocumentsDirectory();
    final resourceDirectory = Directory(
      '${directory.path}${Platform.pathSeparator}StyleItemResources',
    );
    if (resourceDirectory.existsSync()) {
      resourceDirectory.deleteSync(recursive: true);
    }
    resourceDirectory.createSync(recursive: true);

    return resourceDirectory.path;
  }

  // Load the downloaded vector tiles into the map view.
  void _loadExportedVectorTiles(ExportVectorTilesResult? result) {
    final vectorTilesCache = result?.vectorTileCache;
    final itemResourceCache = result?.itemResourceCache;
    if (vectorTilesCache == null || itemResourceCache == null) {
      _showErrorDialog('Invalid vector tiles cache or item resource cache');
      return;
    }
    // Create a new vector tile layer with the downloaded vector tiles.
    final vectorTileLayer = ArcGISVectorTiledLayer.withVectorTileCache(
      vectorTilesCache,
      itemResourceCache: itemResourceCache,
    );
    // display the vector tile layer as a basemap layer in the map view.
    _mapViewController.arcGISMap = ArcGISMap.withBasemap(
      Basemap.withBaseLayer(
        vectorTileLayer,
      ),
    );
    // Display the preview map button.
    setState(() => _previewMap = true);
  }

  // Return a Widget with a red outline.
  Widget buildRedOutline() {
    return IgnorePointer(
      child: SafeArea(
        child: Container(
          margin: const EdgeInsets.fromLTRB(30.0, 30.0, 30.0, 50.0),
          child: Container(
            key: _outlineKey,
            decoration: BoxDecoration(
              border: Border.all(
                color: Colors.red,
                width: 2.0,
              ),
            ),
          ),
        ),
      ),
    );
  }

  // Return a Widget with a linear progress bar.
  Widget buildProgressIndicator() {
    return Container(
      color: Colors.white,
      constraints:
          BoxConstraints(maxWidth: MediaQuery.sizeOf(context).width * 0.6),
      padding: const EdgeInsets.all(20),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Text(
            'Downloading...',
            style: Theme.of(context).textTheme.labelLarge,
          ),
          const SizedBox(height: 20),
          Text(
            '${(_progress * 100).toStringAsFixed(0)}% completed',
            style: Theme.of(context).textTheme.labelMedium,
          ),
          const SizedBox(height: 20),
          LinearProgressIndicator(
            value: _progress,
            backgroundColor: Colors.grey[200],
            color: Colors.blue,
          ),
          const SizedBox(height: 20),
          ElevatedButton(
            onPressed: cancelDownloadingJob,
            child: const Text('Cancel Job'),
          ),
        ],
      ),
    );
  }
}

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