Export vector tiles

View inMAUIWinUIWPFView on GitHub

Export tiles from an online vector tile service.

Export vector tiles

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 "Export vector tiles" button to start exporting the vector tiles. An error will show if the extent is larger than the maximum limit allowed. When finished, a new map view will show the exported result.

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, 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

Vector tiles have high drawing performance and smaller file size compared to regular tiled layers, due to consisting solely of points, lines, and polygons. However, in ArcGIS Maps SDK for .NET they cannot be displayed in scenes. Visit ArcGIS for Developers to learn more about the characteristics of ArcGIS vector tiled layers.

Tags

cache, download, offline, vector

Sample Code

ExportVectorTiles.xaml.csExportVectorTiles.xaml.csExportVectorTiles.xaml
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
// Copyright 2022 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: http://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.

using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Symbology;
using Esri.ArcGISRuntime.Tasks.Offline;
using Esri.ArcGISRuntime.UI;
using Microsoft.UI.Xaml;
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace ArcGIS.WinUI.Samples.ExportVectorTiles
{
    [ArcGIS.Samples.Shared.Attributes.Sample(
        name: "Export vector tiles",
        category: "Layers",
        description: "Export tiles from an online vector tile service.",
        instructions: "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 \"Export vector tiles\" button to start exporting the vector tiles. An error will show if the extent is larger than the maximum limit allowed. When finished, a new map view will show the exported result.",
        tags: new[] { "cache", "download", "offline", "vector" })]
    public partial class ExportVectorTiles
    {
        // Hold references to the variables used in the event handlers.
        private Graphic _downloadArea;
        private ArcGISVectorTiledLayer _vectorTiledLayer;
        private ExportVectorTilesJob _job;

        public ExportVectorTiles()
        {
            InitializeComponent();
            _ = Initialize();
        }

        private async Task Initialize()
        {
            // Create the basemap.
            MyMapView.Map = new Map(BasemapStyle.ArcGISStreetsNight);

            // Load the map to ensure that the tiles are available when the export task is called.
            await MyMapView.Map.LoadAsync();

            // Set the initial viewpoint.
            MyMapView.SetViewpoint(new Viewpoint(34.049, -117.181, 1e4));

            // Create a graphic to show a red outline square around the tiles to be downloaded.
            GraphicsOverlay graphicsOverlay = new GraphicsOverlay();
            _downloadArea = new Graphic()
            {
                Symbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, System.Drawing.Color.Red, 2)
            };
            graphicsOverlay.Graphics.Add(_downloadArea);
            MyMapView.GraphicsOverlays.Add(graphicsOverlay);

            // If the map has loaded check if the basemap layer is a vector tiled layer.
            // If the basemap layer is a vector tiled layer enable the export button.
            if (MyMapView.Map.LoadStatus == Esri.ArcGISRuntime.LoadStatus.Loaded)
            {
                if (MyMapView.Map.Basemap.BaseLayers[0] is ArcGISVectorTiledLayer vectorTiledLayer)
                {
                    _vectorTiledLayer = vectorTiledLayer;
                }

                MyExportButton.IsEnabled = true;
            }
        }

        #region Export Vector Tiles

        private async Task StartExportTask()
        {
            try
            {
                await StartExport();
            }
            catch (Exception e)
            {
                await new MessageDialog2(e.Message, "Error").ShowAsync();
            }
        }

        private async Task StartExport()
        {
            // Create the task.
            ExportVectorTilesTask exportTask = await ExportVectorTilesTask.CreateAsync(_vectorTiledLayer.Source);

            // Get the parameters for the job.
            // The max scale parameter is set to 10% of the map's scale to limit the
            // number of tiles exported to within the vector tiled layer's max tile export limit.
            ExportVectorTilesParameters parameters = await exportTask.CreateDefaultExportVectorTilesParametersAsync(_downloadArea.Geometry, MyMapView.MapScale * 0.1);

            // By using the UseReducedFontService download option the file download speed is reduced.
            // This limits vector tiled layers character sets and may not be suitable in every use case.
            parameters.EsriVectorTilesDownloadOption = EsriVectorTilesDownloadOption.UseReducedFontsService;

            // Get the tile cache path and item resource path for the base layer styling.
            string tilePath = Path.Combine(Environment.ExpandEnvironmentVariables("%TEMP%"), Path.GetTempFileName() + ".vtpk");
            string itemResourcePath = Path.Combine(Environment.ExpandEnvironmentVariables("%TEMP%"), Path.GetTempFileName() + "_styleItemResources");

            // Create the export job.
            _job = exportTask.ExportVectorTiles(parameters, tilePath, itemResourcePath);

            // Update the UI.
            MyProgressBar.Value = 0;
            MyProgressBar.Visibility = Visibility.Visible;
            MyProgressBarLabel.Visibility = Visibility.Visible;
            MyCancelJobButton.Visibility = Visibility.Visible;

            // Add an event handler to update the progress bar as the task progresses.
            _job.ProgressChanged += Job_ProgressChanged;

            // Add an event handler to hide the cancel job button if the job completes, fails or is cancelled.
            _job.StatusChanged += Job_StatusChanged;

            // Start the export job.
            _job.Start();

            // Wait for the job to complete.
            ExportVectorTilesResult vectorTilesResult = await _job.GetResultAsync();

            // Update the preview map and UI components.
            await HandleExportCompleted(vectorTilesResult);
        }

        private async Task HandleExportCompleted(ExportVectorTilesResult vectorTilesResult)
        {
            if (_job.Status == Esri.ArcGISRuntime.Tasks.JobStatus.Succeeded)
            {
                // Show the exported tiles on the preview map.
                await UpdatePreviewMap(vectorTilesResult);

                // Update the UI.
                MyPreviewMapView.Visibility = Visibility.Visible;
                MyClosePreviewButton.Visibility = Visibility.Visible;
                MyExportButton.Visibility = Visibility.Collapsed;
                MyProgressBar.Visibility = Visibility.Collapsed;
                MyProgressBarLabel.Visibility = Visibility.Collapsed;
            }
            else if (_job.Status == Esri.ArcGISRuntime.Tasks.JobStatus.Failed)
            {
                // Notify the user.
                await new MessageDialog2("Job failed").ShowAsync();

                // Hide the progress bar.
                MyProgressBar.Visibility = Visibility.Collapsed;
            }

            // Remove the event handlers.
            _job.ProgressChanged -= Job_ProgressChanged;
            _job.StatusChanged -= Job_StatusChanged;
        }

        #endregion Export Vector Tiles

        #region Update Preview Map/Extent Graphic

        private void UpdateMapExtentGraphic()
        {
            // Return if MyMapView is null.
            if (MyMapView == null) { return; }

            // Get the new viewpoint.
            Viewpoint myViewPoint = MyMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry);

            // Return if viewpoint is null.
            if (myViewPoint == null) { return; }

            // Get the updated extent for the new viewpoint.
            Envelope extent = myViewPoint.TargetGeometry as Envelope;

            // Return if extent is null.
            if (extent == null) { return; }

            // Create an envelope that is a bit smaller than the extent.
            EnvelopeBuilder envelopeBuilder = new EnvelopeBuilder(extent);
            envelopeBuilder.Expand(0.80);

            // Get the (only) graphics overlay in the map view.
            GraphicsOverlay extentOverlay = MyMapView.GraphicsOverlays.FirstOrDefault();

            // Return if the extent overlay is null.
            if (extentOverlay == null) { return; }

            // Get the extent graphic.
            Graphic extentGraphic = extentOverlay.Graphics.FirstOrDefault();

            // Create the extent graphic and add it to the overlay if it doesn't exist.
            if (extentGraphic == null)
            {
                extentGraphic = new Graphic(envelopeBuilder.ToGeometry());
                extentOverlay.Graphics.Add(extentGraphic);
            }
            else
            {
                // Otherwise, simply update the graphic's geometry.
                extentGraphic.Geometry = envelopeBuilder.ToGeometry();
            }
        }

        private async Task UpdatePreviewMap(ExportVectorTilesResult vectorTilesResult)
        {
            // Load the vector tile cache.
            VectorTileCache vectorTileCache = vectorTilesResult.VectorTileCache;
            await vectorTileCache.LoadAsync();

            // Create a tile layer from the tile cache.
            ArcGISVectorTiledLayer myLayer = new ArcGISVectorTiledLayer(vectorTileCache, vectorTilesResult.ItemResourceCache);

            // Show the layer in a new map.
            MyPreviewMapView.Map = new Map(new Basemap(myLayer));
        }

        #endregion Update Preview Map/Extent Graphic

        #region EventHandlers

        private void MyMapView_ViewpointChanged(object sender, EventArgs e)
        {
            UpdateMapExtentGraphic();
        }

        private void MyExportButton_Click(object sender, RoutedEventArgs e)
        {
            // Update the UI.
            MyPreviewMapView.Visibility = Visibility.Collapsed;
            MyClosePreviewButton.Visibility = Visibility.Collapsed;
            MyExportButton.Visibility = Visibility.Visible;
            MyExportButton.IsEnabled = false;

            // Start the export.
            _ = StartExportTask();
        }

        private void MyClosePreviewButton_Click(object sender, RoutedEventArgs e)
        {
            // Update the UI.
            MyPreviewMapView.Visibility = Visibility.Collapsed;
            MyClosePreviewButton.Visibility = Visibility.Collapsed;
            MyExportButton.Visibility = Visibility.Visible;
            MyExportButton.IsEnabled = true;
        }

        private void MyCancelJobButton_Click(object sender, RoutedEventArgs e)
        {
            if (_job != null)
            {
                _ = _job.CancelAsync();

                // Remove the event handlers.
                _job.ProgressChanged -= Job_ProgressChanged;
                _job.StatusChanged -= Job_StatusChanged;

                // Update the UI.
                MyCancelJobButton.Visibility = Visibility.Collapsed;
                MyProgressBar.Visibility = Visibility.Collapsed;
                MyProgressBarLabel.Visibility = Visibility.Collapsed;
                MyExportButton.IsEnabled = true;
            }
        }

        private void Job_ProgressChanged(object sender, EventArgs e)
        {
            DispatcherQueue.TryEnqueue(() =>
            {
                MyProgressBar.Value = _job.Progress;
                MyProgressBarLabel.Text = $"{MyProgressBar.Value}%";
            });
        }

        private void Job_StatusChanged(object sender, Esri.ArcGISRuntime.Tasks.JobStatus e)
        {
            DispatcherQueue.TryEnqueue(() =>
            {
                bool showCancelJobButton = (_job.Status != Esri.ArcGISRuntime.Tasks.JobStatus.Failed &&
                                            _job.Status != Esri.ArcGISRuntime.Tasks.JobStatus.Succeeded &&
                                            _job.Status != Esri.ArcGISRuntime.Tasks.JobStatus.Canceling);

                MyCancelJobButton.Visibility = showCancelJobButton ? Visibility.Visible : Visibility.Collapsed;
            });
        }

        #endregion EventHandlers
    }
}

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