Apply scheduled updates to preplanned map area

View on GitHub

Apply scheduled updates to a downloaded preplanned map area.

Image of apply scheduled updates to preplanned map area

Use case

With scheduled updates, the author can update the features within the preplanned areas on the service once, and multiple end-users can request these updates to bring their local copies up to date with the most recent state. Importantly, any number of end-users can download the same set of cached updates which means that this workflow is extremely scalable for large operations where you need to minimize load on the server.

This workflow can be used by survey workers operating in remote areas where network connectivity is not available. The workers could download mobile map packages to their individual devices and perform their work normally. Once they regain internet connectivity, the mobile map packages can be updated to show any new features that have been added to the online service.

How to use the sample

Start the app. It will display an offline map, check for available updates, and show update availability and size. Select 'Apply Updates' to apply the updates to the local offline map and show the results.

How it works

  1. Create an OfflineMapSyncTask with your offline map.
  2. If desired, get OfflineMapUpdatesInfo from the task to check for update availability or update size.
  3. Get a set of default OfflineMapSyncParameters for the task.
  4. Set the parameters to download all available updates.
  5. Use the parameters to create an OfflineMapSyncJob.
  6. Start the job and get the results once it completes successfully.
  7. Check if the mobile map package needs to be reopened, and do so if necessary.
  8. Finally, display your offline map to see the changes.

Relevant API

  • MobileMapPackage
  • OfflineMapSyncJob
  • OfflineMapSyncParameters
  • OfflineMapSyncResult
  • OfflineMapSyncTask
  • OfflineMapUpdatesInfo

About the data

The data in this sample shows the roads and trails in the Canyonlands National Park, Utah. Data by U.S. National Parks Service. No claim to original U.S. Government works.

Additional information

Note: preplanned areas using the Scheduled Updates workflow are read-only. For preplanned areas that can be edited on the end-user device, see the Download preplanned map area sample. For more information about offline workflows, see Offline maps, scenes, and data in the ArcGIS Developers guide.

Tags

offline, pre-planned, preplanned, synchronize, update

Sample Code

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

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

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

  @override
  State<ApplyScheduledUpdatesToPreplannedMapArea> createState() =>
      _ApplyScheduledUpdatesToPreplannedMapAreaState();
}

class _ApplyScheduledUpdatesToPreplannedMapAreaState
    extends State<ApplyScheduledUpdatesToPreplannedMapArea>
    with SampleStateSupport {
  // Create a controller for the map view.
  final _mapViewController = ArcGISMapView.createController();
  // Flag indicating if an update is avalable for the map package.
  var _canUpdate = false;
  // Flag that will be set to true when all properties have been initialized.
  var _ready = false;
  // Status of the update availability.
  var _updateStatus = OfflineUpdateAvailability.indeterminate;
  // Size in KB of the available update.
  var _updateSizeKB = 0.0;
  // The Active mobile map package.
  MobileMapPackage? _mobileMapPackage;
  // Offline task and parameters used for updating the map package.
  late OfflineMapSyncTask _offlineMapSyncTask;
  late OfflineMapSyncParameters _mapSyncParameters;
  // The location of the map package on the device.
  late final Uri _dataUri;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        top: false,
        child: Stack(
          children: [
            Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              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: [
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        Text('Updates: ${_updateStatus.name.toUpperCase()}'),
                        Text('Update Size: ${_updateSizeKB}KB'),
                      ],
                    ),
                    Center(
                      child: ElevatedButton(
                        // Disable the button if no update is available.
                        onPressed: _canUpdate ? syncUpdates : null,
                        child: const Text('Apply Updates'),
                      ),
                    ),
                  ],
                ),
              ],
            ),
            // Display a progress indicator and prevent interaction before state is ready.
            Visibility(
              visible: !_ready,
              child: SizedBox.expand(
                child: Container(
                  color: Colors.white30,
                  child: const Center(child: CircularProgressIndicator()),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  void onMapViewReady() async {
    // Set the path to the map package data.
    final appDir = await getApplicationDocumentsDirectory();
    _dataUri = Uri.parse('${appDir.absolute.path}/canyonlands');

    // Prepare (download and extract) the map package data.
    await _prepareData();

    // Check if there is an update for the map package.
    await _checkForUpdates();

    setState(() => _ready = true);
  }

  // Perform the map data update.
  Future<void> syncUpdates() async {
    setState(() => _canUpdate = false);

    final mapSyncJob =
        _offlineMapSyncTask.syncOfflineMap(parameters: _mapSyncParameters);
    try {
      await mapSyncJob.run();
      final result = mapSyncJob.result;
      if (result != null && result.isMobileMapPackageReopenRequired) {
        await _loadMapPackageMap();
      }
    } catch (err) {
      if (mounted) {
        _showAlertDialog(
          'The offline map sync failed with error: {$err}.',
          title: 'Error',
        );
      }
    } finally {
      // Refresh the update status.
      await _checkForUpdates();
    }
  }

  // Function to check for map package updates.
  Future<void> _checkForUpdates() async {
    final updatesInfo = await _offlineMapSyncTask.checkForUpdates();
    setState(() {
      _updateStatus = updatesInfo.downloadAvailability;
      _updateSizeKB = updatesInfo.scheduledUpdatesDownloadSize / 1024;
      _canUpdate = updatesInfo.downloadAvailability ==
          OfflineUpdateAvailability.available;
    });
  }

  // Load the map package into the map.
  Future<bool> _loadMapPackageMap() async {
    // Reset the map package.
    _mobileMapPackage?.close();
    _mobileMapPackage = null;
    _mobileMapPackage = MobileMapPackage.withFileUri(_dataUri);

    // Try to load the map package.
    try {
      await _mobileMapPackage!.load();
    } catch (err) {
      if (mounted) {
        _showAlertDialog(
          'Mobile Map Package failed to load with error: {$err}',
          title: 'Error',
        );
      }
      return false;
    }

    if (_mobileMapPackage!.maps.isEmpty) {
      if (mounted) {
        _showAlertDialog('Mobile map package contains no maps.');
      }
      return false;
    }

    // Load the first map in the package.
    _mapViewController.arcGISMap = _mobileMapPackage!.maps.first;

    // Set the offline map sync task.
    _offlineMapSyncTask =
        OfflineMapSyncTask.withMap(_mapViewController.arcGISMap!);

    // Set the map sync parameters.
    _mapSyncParameters =
        await _offlineMapSyncTask.createDefaultOfflineMapSyncParameters()
          ..syncDirection = SyncDirection.none
          ..preplannedScheduledUpdatesOption =
              PreplannedScheduledUpdatesOption.downloadAllUpdates
          ..rollbackOnFailure = true;

    return true;
  }

  // Function that extracts the map package archive to restore the original map data.
  // Downloads and extracts the map package archive if the file is not currently on the device.
  Future<void> _prepareData() async {
    final archiveFile = File.fromUri(Uri.parse('${_dataUri.path}.zip'));
    if (archiveFile.existsSync()) {
      // The map package is already downladed. Extract it.
      await extractZipArchive(archiveFile);
    } else {
      // Download the map package and extract it.
      await downloadSampleData(['740b663bff5e4198b9b6674af93f638a']);
    }

    // Load the map package from the extracted map package.
    await _loadMapPackageMap();
  }

  // Utility function to show an alert dialog with a provided message.
  Future<void> _showAlertDialog(String message, {String title = 'Alert'}) {
    return showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(title),
        content: Text(message),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context, 'OK'),
            child: const Text('OK'),
          ),
        ],
      ),
    );
  }
}

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