Пример #1
0
        /// <summary>
        /// Method that handles downloading the map into an offline map package
        /// </summary>
        private async Task DownloadPackageAsync(Envelope extent)
        {
            var syncTask = await OfflineMapTask.CreateAsync(_map);

            try
            {
                // set extent based on screen
                var parameters = await syncTask.CreateDefaultGenerateOfflineMapParametersAsync(extent);

                // set the job to generate the offline map
                GenerateOfflineMapJob = syncTask.GenerateOfflineMap(parameters, _downloadPath);

                // update the progress property when progress changes
                GenerateOfflineMapJob.ProgressChanged +=
                    (s, e) =>
                {
                    Progress = GenerateOfflineMapJob.Progress;
                };

                // listen for job changed events
                GenerateOfflineMapJob.JobChanged += GenerateOfflineMapJob_JobChanged;

                // begin download job
                GenerateOfflineMapJob.Start();
            }
            catch (Exception ex)
            {
                UserPromptMessenger.Instance.RaiseMessageValueChanged(
                    null, ex.Message, true, ex.StackTrace);
            }
        }
Пример #2
0
        private async Task DownloadPreplannedMap()
        {
            var downloadTask = await OfflineMapTask.CreateAsync(TheMap.Map);

            var areas = await downloadTask.GetPreplannedMapAreasAsync();

            var firstArea = areas.First();
            await firstArea.LoadAsync();

            var parameters = await downloadTask.CreateDefaultDownloadPreplannedOfflineMapParametersAsync(firstArea);

            parameters.ContinueOnErrors = false;
            parameters.IncludeBasemap   = true;
            var job = downloadTask.DownloadPreplannedOfflineMap(parameters, PreplannedDataFolder);

            job.ProgressChanged += PreplannedJob_ProgressChanged;
            var result = await job.GetResultAsync();

            if (!result.HasErrors)
            {
                PreplannedStatusLabel.Text      = "Preplanned Map: Download complete.";
                PreplannedStatusLabel.TextColor = Color.Green;
                _preplannedMap = result.OfflineMap;
            }
            else
            {
                PreplannedStatusLabel.Text      = "Preplanned Map: Completed with errors.";
                PreplannedStatusLabel.TextColor = Color.Red;
            }

            ConditionallyEnableStep2();
        }
Пример #3
0
        private async Task DownloadOnDemandMap()
        {
            var downloadTask = await OfflineMapTask.CreateAsync(TheMap.Map);

            var parameters = await downloadTask.CreateDefaultGenerateOfflineMapParametersAsync(TheMap.GetCurrentViewpoint(ViewpointType.BoundingGeometry).TargetGeometry);

            parameters.AttachmentSyncDirection     = AttachmentSyncDirection.None;
            parameters.ReturnLayerAttachmentOption = ReturnLayerAttachmentOption.None;
            var job = downloadTask.GenerateOfflineMap(parameters, OnDemandDataFolder);

            job.ProgressChanged += OnDemandJob_ProgressChanged;
            var result = await job.GetResultAsync();

            if (!result.HasErrors)
            {
                OnDemandStatusLabel.Text      = "OnDemand Map: Download complete.";
                OnDemandStatusLabel.TextColor = Color.Green;
                _onDemandMap = result.OfflineMap;
            }
            else
            {
                OnDemandStatusLabel.Text      = "OnDemand Map: Completed with errors.";
                OnDemandStatusLabel.TextColor = Color.Red;
            }

            ConditionallyEnableStep2();
        }
Пример #4
0
        private async void CanBeTakenOffline(OfflineMapTask task, GenerateOfflineMapParameters parameters)
        {
            OfflineMapCapabilities results = await task.GetOfflineMapCapabilitiesAsync(parameters);

            if (results.HasErrors)
            {
                // Handle possible errors with layers
                foreach (var layerCapability in results.LayerCapabilities)
                {
                    if (!layerCapability.Value.SupportsOffline)
                    {
                        Debug.WriteLine(layerCapability.Key.Name + " cannot be taken offline. Error : " + layerCapability.Value.Error.Message);
                    }
                }


                // Handle possible errors with tables
                foreach (var tableCapability in results.TableCapabilities)
                {
                    if (!tableCapability.Value.SupportsOffline)
                    {
                        Debug.WriteLine(tableCapability.Key.TableName + " cannot be taken offline. Error : " + tableCapability.Value.Error.Message);
                    }
                }
            }
            else
            {
                // All layers and tables can be taken offline!
                MessageBox.Show("All layers are good to go!");
                Debug.WriteLine("All layers are good to go!");
            }
        }
        private async void TakeMapOfflineButton_Click(object sender, EventArgs e)
        {
            // Create a path for the output mobile map.
            string tempPath = $"{Path.GetTempPath()}";

            string[] outputFolders = Directory.GetDirectories(tempPath, "NapervilleWaterNetwork*");

            // Loop through the folder names and delete them.
            foreach (string dir in outputFolders)
            {
                try
                {
                    // Delete the folder.
                    Directory.Delete(dir, true);
                }
                catch (Exception)
                {
                    // Ignore exceptions (files might be locked, for example).
                }
            }

            // Create a new folder for the output mobile map.
            _packagePath = Path.Combine(tempPath, @"NapervilleWaterNetwork");
            int num = 1;

            while (Directory.Exists(_packagePath))
            {
                _packagePath = Path.Combine(tempPath, @"NapervilleWaterNetwork" + num.ToString());
                num++;
            }

            // Create the output directory.
            Directory.CreateDirectory(_packagePath);

            try
            {
                // Create an offline map task with the current (online) map.
                _takeMapOfflineTask = await OfflineMapTask.CreateAsync(_mapView.Map);

                // Create the default parameters for the task, pass in the area of interest.
                _parameters = await _takeMapOfflineTask.CreateDefaultGenerateOfflineMapParametersAsync(_areaOfInterest);

                // Get the overrides.
                _overrides = await _takeMapOfflineTask.CreateGenerateOfflineMapParameterOverridesAsync(_parameters);

                // Create the overrides UI.
                ParameterOverrideFragment overlayFragment = new ParameterOverrideFragment(_overrides, _mapView.Map);

                // Complete configuration when the dialog is closed.
                overlayFragment.FinishedConfiguring += ConfigurationContinuation;

                // Display the configuration window.
                overlayFragment.Show(FragmentManager, "");
            }
            catch (Exception ex)
            {
                // Exception while taking the map offline.
                ShowStatusMessage(ex.Message);
            }
        }
Пример #6
0
        private static async Task DownloadMapAsync(PortalItem portalItem)
        {
            Map onlineMap          = new Map(portalItem);
            var takeMapOfflineTask = await OfflineMapTask.CreateAsync(onlineMap);

            // Create the job to generate an offline map, pass in the parameters and a path to
            //store the map package.
            var parameters = new GenerateOfflineMapParameters()
            {
                MaxScale       = 5000,
                IncludeBasemap = true,
            };
            var path = MapAreaManager.GetOfflineMapPath("reference_base_map", true);

            GenerateOfflineMapJob generateMapJob =
                takeMapOfflineTask.GenerateOfflineMap(parameters, path);

            // Generate the offline map and download it.
            GenerateOfflineMapResult offlineMapResult = await generateMapJob.GetResultAsync();

            if (!offlineMapResult.HasErrors)
            {
                // Job completed successfully and all content was generated.
                Debug.WriteLine("Map " +
                                offlineMapResult.MobileMapPackage.Item.Title +
                                " was saved to " +
                                offlineMapResult.MobileMapPackage.Path);
            }
            else
            {
                // Job is finished but one or more layers or tables had errors.
                if (offlineMapResult.LayerErrors.Count > 0)
                {
                    // Show layer errors.
                    foreach (var layerError in offlineMapResult.LayerErrors)
                    {
                        Debug.WriteLine("Error occurred when taking " +
                                        layerError.Key.Name +
                                        " offline. Error : " +
                                        layerError.Value.Message);
                    }
                }
                if (offlineMapResult.TableErrors.Count > 0)
                {
                    // Show table errors.
                    foreach (var tableError in offlineMapResult.TableErrors)
                    {
                        Debug.WriteLine("Error occurred when taking " +
                                        tableError.Key.TableName +
                                        " offline. Error : " +
                                        tableError.Value.Message);
                    }
                }
            }
        }
        private async void Initialize()
        {
            try
            {
                // The data manager provides a method to get a suitable offline data folder.
                _offlineDataFolder = Path.Combine(DataManager.GetDataFolder(), "SampleData", "DownloadPreplannedMapAreas");

                // If temporary data folder doesn't exists, create it.
                if (!Directory.Exists(_offlineDataFolder))
                {
                    Directory.CreateDirectory(_offlineDataFolder);
                }

                // Create a portal to enable access to the portal item.
                ArcGISPortal portal = await ArcGISPortal.CreateAsync();

                // Create the portal item from the portal item ID.
                PortalItem webMapItem = await PortalItem.CreateAsync(portal, PortalItemId);

                // Show the map.
                _originalMap   = new Map(webMapItem);
                _myMapView.Map = _originalMap;

                // Create an offline map task for the web map item.
                _offlineMapTask = await OfflineMapTask.CreateAsync(webMapItem);

                // Find the available preplanned map areas.
                IReadOnlyList <PreplannedMapArea> preplannedAreas = await _offlineMapTask.GetPreplannedMapAreasAsync();

                // Load each item, then add it to the list of areas.
                foreach (PreplannedMapArea area in preplannedAreas)
                {
                    await area.LoadAsync();

                    _mapAreas.Add(area);
                }

                // Configure the table view for showing map areas.
                _mapAreaViewModel              = new MapAreaViewModel(_mapAreas);
                _mapAreaViewModel.MapSelected += _mapAreaViewModel_MapSelected;

                _tableController = new UITableViewController(UITableViewStyle.Plain);
                _tableController.TableView.Source = _mapAreaViewModel;

                // Hide the loading indicator.
                _activityIndicator.StopAnimating();
            }
            catch (Exception ex)
            {
                // Something unexpected happened, show the error message.
                Debug.WriteLine(ex);
                new UIAlertView("There was an error", ex.ToString(), (IUIAlertViewDelegate)null, "OK", null).Show();
            }
        }
        private async void Initialize()
        {
            try
            {
                // Get the offline data folder.
                _offlineDataFolder = Path.Combine(GetDataFolder(),
                                                  "SampleData", "DownloadPreplannedMapAreas");

                // If the temporary data folder doesn't exist, create it.
                if (!Directory.Exists(_offlineDataFolder))
                {
                    Directory.CreateDirectory(_offlineDataFolder);
                }

                // Create a portal that contains the portal item.
                ArcGISPortal portal = await ArcGISPortal.CreateAsync();

                // Create the webmap based on the id.
                PortalItem webmapItem = await PortalItem.CreateAsync(portal, PortalItemId);

                // Create the offline task and load it.
                _offlineMapTask = await OfflineMapTask.CreateAsync(webmapItem);

                // Query related preplanned areas.
                IReadOnlyList <PreplannedMapArea> preplannedAreas = await _offlineMapTask.GetPreplannedMapAreasAsync();

                // Load each preplanned map area and add it to the flyout list.
                foreach (PreplannedMapArea area in preplannedAreas)
                {
                    await area.LoadAsync();

                    // Add item to the flyout list (for mobile).
                    MenuFlyoutItem menuItem = new MenuFlyoutItem {
                        Text = area.PortalItem.Title, DataContext = area
                    };
                    menuItem.Click += OnMenuDownloadMapAreaClicked;
                    MapAreaFlyout.Items?.Add(menuItem);
                }

                // Show the areas in the UI. The code to make this look nice in the UI is defined
                //    in the ListView's ItemTemplate in the XAML.
                PreplannedAreasList.ItemsSource = preplannedAreas;

                // Remove loading indicators from UI.
                DownloadNotificationText.Visibility = Visibility.Visible;
                BusyIndicator.Visibility            = Visibility.Collapsed;
            }
            catch (Exception ex)
            {
                // Something unexpected happened, show the error message.
                MessageDialog message = new MessageDialog(ex.Message, "An error occurred");
                await message.ShowAsync();
            }
        }
Пример #9
0
        public async void generateOfflineMap()
        {
            OfflineMapTask task = await OfflineMapTask.CreateAsync(mapView.Map);

            Envelope initialLocation = new Envelope(375474, 120000, 422020, 152000, new SpatialReference(26985));
            GenerateOfflineMapParameters parameters =
                await task.CreateDefaultGenerateOfflineMapParametersAsync(initialLocation);


            GenerateOfflineMapJob    generateMapJob = task.GenerateOfflineMap(parameters, "C:\\RuntimeArcgis");
            GenerateOfflineMapResult results        = await generateMapJob.GetResultAsync();
        }
Пример #10
0
        private async void CreateOfflineMapTask()
        {
            AuthenticationManager.Current.ChallengeHandler = new Esri.ArcGISRuntime.Security.ChallengeHandler(CreateKnownCredentials);

            // Create task and set parameters
            OfflineMapTask task = await OfflineMapTask.CreateAsync(MyMapView.Map);

            GenerateOfflineMapParameters parameters = await GenerateGeodatabaseParameters(task, webmapItem);

            CanBeTakenOffline(task, parameters);
            GenerateOfflineMap(task, parameters);
        }
        private async void QueryMapAreas()
        {
            try
            {
                // Clear existing overlays
                _mapViewService.ClearOverlays();

                // Clear existing areas (in case user wants to refresh results)
                MapAreas.Clear();

                // Create new task to
                var offlineMapTask = await OfflineMapTask.CreateAsync(Map);

                // Get list of areas
                IReadOnlyList <PreplannedMapArea> preplannedMapAreas = await offlineMapTask.GetPreplannedMapAreasAsync();

                // Create UI from the areas
                foreach (var preplannedMapArea in preplannedMapAreas.OrderBy(x => x.PortalItem.Title))
                {
                    // Load area to get the metadata
                    await preplannedMapArea.LoadAsync();

                    // Using a custom model for easier visualization
                    var model = new MapAreaModel(preplannedMapArea);
                    MapAreas.Add(model);
                    // Graphic that shows the area in the map
                    var graphic = new Graphic(preplannedMapArea.AreaOfInterest, GetSymbolForColor(model.DisplayColor));
                    graphic.Attributes.Add("Name", preplannedMapArea.PortalItem.Title);
                    _areasOverlay.Graphics.Add(graphic);
                }

                if (!preplannedMapAreas.Any())
                {
                    await _windowService.ShowAlertAsync("No preplanned map areas available.");
                }
                else
                {
                    // Show the overlays on the map
                    _mapViewService.AddGraphicsOverlay(_areasOverlay);

                    // Zoom to the offline areas
                    await _mapViewService.SetViewpointGeometryAsync(_areasOverlay.Extent, 20);
                }

                // Refresh commands
                RefreshCommands();
            }
            catch (Exception ex)
            {
                await _windowService.ShowAlertAsync(ex.Message, "Couldn't query map areas");
            }
        }
        private async void Initialize()
        {
            try
            {
                // The data manager provides a method to get a suitable offline data folder.
                _offlineDataFolder = Path.Combine(DataManager.GetDataFolder(), "SampleData", "DownloadPreplannedMapAreas");



                // If temporary data folder doesn't exists, create it.
                if (!Directory.Exists(_offlineDataFolder))
                {
                    Directory.CreateDirectory(_offlineDataFolder);
                }

                // Create a portal to enable access to the portal item.
                ArcGISPortal portal = await ArcGISPortal.CreateAsync();

                // Create the portal item from the portal item ID.
                PortalItem webMapItem = await PortalItem.CreateAsync(portal, PortalItemId);

                // Show the map.
                _originalMap   = new Map(webMapItem);
                _myMapView.Map = _originalMap;

                // Create an offline map task for the web map item.
                _offlineMapTask = await OfflineMapTask.CreateAsync(webMapItem);

                // Find the available preplanned map areas.
                IReadOnlyList <PreplannedMapArea> preplannedAreas = await _offlineMapTask.GetPreplannedMapAreasAsync();

                // Load each item, then add it to the list of areas.
                foreach (PreplannedMapArea area in preplannedAreas)
                {
                    await area.LoadAsync();

                    _mapAreas.Add(area);
                }

                // Show the map areas in the UI.
                ConfigureMapsButtons();

                // Hide the loading indicator.
                _progressView.Dismiss();
            }
            catch (Exception ex)
            {
                // Something unexpected happened, show the error message.
                Debug.WriteLine(ex);
                new AlertDialog.Builder(this).SetMessage(ex.ToString()).SetTitle("There was an error.").Show();
            }
        }
        private async void Initialize()
        {
            try
            {
                // Show a loading indicator.
                View.AddSubview(_progressIndicator);
                _progressIndicator.UpdateMessageAndProgress("Loading list of available map areas.", -1);

                // Get the offline data folder.
                _offlineDataFolder = Path.Combine(GetDataFolder(),
                                                  "SampleData", "DownloadPreplannedMapAreas");

                // If the temporary data folder doesn't exist, create it.
                if (!Directory.Exists(_offlineDataFolder))
                {
                    Directory.CreateDirectory(_offlineDataFolder);
                }

                // Create a portal that contains the portal item.
                ArcGISPortal portal = await ArcGISPortal.CreateAsync();

                // Create the webmap based on the id.
                PortalItem webmapItem = await PortalItem.CreateAsync(portal, PortalItemId);

                // Create the offline map task and load it.
                _offlineMapTask = await OfflineMapTask.CreateAsync(webmapItem);

                // Query related preplanned areas.
                _preplannedMapAreas = await _offlineMapTask.GetPreplannedMapAreasAsync();

                // Load each preplanned map area.
                foreach (var area in _preplannedMapAreas)
                {
                    await area.LoadAsync();
                }

                // Show a popup menu of available areas when the download button is clicked.
                _downloadButton.TouchUpInside += DownloadButton_Click;

                // Remove loading indicators from UI.
                _progressIndicator.RemoveFromSuperview();
            }
            catch (Exception ex)
            {
                // Something unexpected happened, show the error message.
                UIAlertController alertController = UIAlertController.Create("An error occurred.", ex.Message, UIAlertControllerStyle.Alert);
                alertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                PresentViewController(alertController, true, null);
            }
        }
        private async void Initialize()
        {
            try
            {
                // The data manager provides a method to get a suitable offline data folder.
                _offlineDataFolder = Path.Combine(DataManager.GetDataFolder(), "SampleData", "DownloadPreplannedMapAreas");

                // If temporary data folder doesn't exists, create it.
                if (!Directory.Exists(_offlineDataFolder))
                {
                    Directory.CreateDirectory(_offlineDataFolder);
                }

                // Create a portal to enable access to the portal item.
                ArcGISPortal portal = await ArcGISPortal.CreateAsync();

                // Create the portal item from the portal item ID.
                PortalItem webMapItem = await PortalItem.CreateAsync(portal, PortalItemId);

                // Show the map.
                _originalMap  = new Map(webMapItem);
                MyMapView.Map = _originalMap;

                // Create an offline map task for the web map item.
                _offlineMapTask = await OfflineMapTask.CreateAsync(webMapItem);

                // Find the available preplanned map areas.
                IReadOnlyList <PreplannedMapArea> preplannedAreas = await _offlineMapTask.GetPreplannedMapAreasAsync();

                // Load each item, then add it to the list of areas.
                foreach (PreplannedMapArea area in preplannedAreas)
                {
                    await area.LoadAsync();

                    _mapAreas.Add(area);
                }

                // Show the map areas in the UI.
                AreasList.ItemsSource = _mapAreas;

                // Hide the loading indicator.
                BusyIndicator.IsVisible = false;
            }
            catch (Exception ex)
            {
                // Something unexpected happened, show the error message.
                Debug.WriteLine(ex);
                await Application.Current.MainPage.DisplayAlert("There was an error.", ex.Message, "OK");
            }
        }
        private async void Initialize()
        {
            try
            {
                // Close the current mobile package when the sample closes.
                Unloaded += (s, e) => { _mobileMapPackage?.Close(); };

                // The data manager provides a method to get a suitable offline data folder.
                _offlineDataFolder = Path.Combine(DataManager.GetDataFolder(), "SampleData", "DownloadPreplannedMapAreas");

                // If temporary data folder doesn't exists, create it.
                if (!Directory.Exists(_offlineDataFolder))
                {
                    Directory.CreateDirectory(_offlineDataFolder);
                }

                // Create a portal to enable access to the portal item.
                ArcGISPortal portal = await ArcGISPortal.CreateAsync();

                // Create the portal item from the portal item ID.
                PortalItem webMapItem = await PortalItem.CreateAsync(portal, PortalItemId);

                // Show the map.
                _originalMap  = new Map(webMapItem);
                MyMapView.Map = _originalMap;

                // Create an offline map task for the web map item.
                _offlineMapTask = await OfflineMapTask.CreateAsync(webMapItem);

                // Find the available preplanned map areas.
                IReadOnlyList <PreplannedMapArea> preplannedAreas = await _offlineMapTask.GetPreplannedMapAreasAsync();

                // Load each item, then add it to the UI.
                foreach (PreplannedMapArea area in preplannedAreas)
                {
                    await area.LoadAsync();

                    AreasList.Items.Add(area);
                }

                // Hide the loading indicator.
                BusyIndicator.Visibility = Visibility.Collapsed;
            }
            catch (Exception ex)
            {
                // Something unexpected happened, show the error message.
                Debug.WriteLine(ex);
                await new MessageDialog(ex.Message, "There was an error.").ShowAsync();
            }
        }
        public async void init()

        {
            try
            {
                MobileMapPackage offlineMapPackage = await MobileMapPackage.OpenAsync("C:/TEMPCD");



                // Get the map from the package and set it to the MapView
                var map = offlineMapPackage.Maps.First();
                Map = map;
            }
            catch (Exception e)
            {
                ArcGISPortal portal = await ArcGISPortal.CreateAsync();

                // Get a web map item using its ID.
                PortalItem webmapItem = await PortalItem.CreateAsync(portal, "a72f2553da664a41b5f00583f7780206");

                // Create a map from the web map item.
                _map = new Map(webmapItem);
                Map  = _map;
                // Create an OfflineMapTask from the map ...
                OfflineMapTask takeMapOfflineTask = await OfflineMapTask.CreateAsync(_map);

                // ... or a web map portal item.



                // Create the default parameters for the task, pass in the area of interest.
                GenerateOfflineMapParameters parameters = await takeMapOfflineTask.CreateDefaultGenerateOfflineMapParametersAsync(new Envelope(375474, 120000, 422020, 152000, new SpatialReference(26985)));

                // Create the job with the parameters and output location.
                var _generateOfflineMapJob = takeMapOfflineTask.GenerateOfflineMap(parameters, "C:/TEMPCD");

                // Handle the progress changed event for the job.
                // _generateOfflineMapJob.ProgressChanged += OfflineMapJob_ProgressChanged;

                // Await the job to generate geodatabases, export tile packages, and create the mobile map package.
                GenerateOfflineMapResult results = await _generateOfflineMapJob.GetResultAsync();

                Map = results.OfflineMap;
            }
        }
        private async void Initialize()
        {
            try
            {
                // Get the offline data folder.
                _offlineDataFolder = Path.Combine(GetDataFolder(),
                                                  "SampleData", "DownloadPreplannedMapAreas");

                // If the temporary data folder doesn't exist, create it.
                if (!Directory.Exists(_offlineDataFolder))
                {
                    Directory.CreateDirectory(_offlineDataFolder);
                }

                // Create a portal that contains the portal item.
                ArcGISPortal portal = await ArcGISPortal.CreateAsync();

                // Create webmap based on the ID.
                PortalItem webmapItem = await PortalItem.CreateAsync(portal, PortalItemId);

                // Create the offline map task and load it.
                _offlineMapTask = await OfflineMapTask.CreateAsync(webmapItem);

                // Query related preplanned areas.
                IReadOnlyList <PreplannedMapArea> preplannedAreas = await _offlineMapTask.GetPreplannedMapAreasAsync();

                // Load each preplanned map area.
                foreach (PreplannedMapArea area in preplannedAreas)
                {
                    await area.LoadAsync();
                }

                // Show the areas in the UI.
                PreplannedAreasList.ItemsSource = preplannedAreas;

                // Remove loading indicators from UI.
                BusyIndicator.IsVisible = false;
            }
            catch (Exception ex)
            {
                // Something unexpected happened, show the error message.
                await((Page)Parent).DisplayAlert("An error occurred", ex.Message, "OK");
            }
        }
Пример #18
0
        internal static async Task <List <MapArea> > GetMapAreasAsync(string mapId)
        {
            ArcGISPortal arcGISOnline = await ArcGISPortal.CreateAsync();

            var portalItem = await PortalItem.CreateAsync(arcGISOnline, mapId);

            var offlineTask = await OfflineMapTask.CreateAsync(portalItem);

            var mapAreas = await offlineTask.GetPreplannedMapAreasAsync();

            var model = new List <MapArea>();

            foreach (PreplannedMapArea mapArea in mapAreas)
            {
                await mapArea.LoadAsync();

                PortalItem preplannedMapItem = mapArea.PortalItem;
                var        thumbnail         = await preplannedMapItem.Thumbnail.ToImageSourceAsync();

                var path = MapAreaManager.GetOfflineMapPath(preplannedMapItem.ItemId);
                var offlineMapPackage = default(MobileMapPackage);
                try
                {
                    offlineMapPackage = await MobileMapPackage.OpenAsync(path);
                } catch (FileNotFoundException)
                {
                    /* this is expected when the map has not been downloaded yet */
                }

                model.Add(new MapArea()
                {
                    Id            = preplannedMapItem.ItemId,
                    Title         = preplannedMapItem.Title,
                    Thumbnail     = thumbnail,
                    Snippet       = preplannedMapItem.Snippet,
                    Payload       = mapArea,
                    OfflineTask   = offlineTask,
                    IsDownloaded  = (offlineMapPackage != null),
                    IsDownloading = false
                });
            }

            return(model);
        }
Пример #19
0
        private async void GenerateOfflineMap(OfflineMapTask task, GenerateOfflineMapParameters parameters)
        {
            string pathToOutputPackage = @"C:\My Documents\Readiness\Trainings\Runtime 100.1\Demos\OfflineMap";
            // Create a job and provide needed parameters
            GenerateOfflineMapJob job = task.GenerateOfflineMap(parameters, pathToOutputPackage);


            // Generate the offline map and download it
            GenerateOfflineMapResult results = await job.GetResultAsync();


            if (!results.HasErrors)
            {
                // Job is finished and all content was generated
                Debug.WriteLine("Map " + results.MobileMapPackage.Item.Title + " saved to " + results.MobileMapPackage.Path);


                // Show offline map in a MapView
                MyMapView.Map = results.OfflineMap;
            }
            else
            {
                // Job is finished but some of the layers/tables had errors
                if (results.LayerErrors.Count > 0)
                {
                    foreach (var layerError in results.LayerErrors)
                    {
                        Debug.WriteLine("Error occurred when taking " + layerError.Key.Name + " offline. Error : " + layerError.Value.Message);
                    }
                }
                if (results.TableErrors.Count > 0)
                {
                    foreach (var tableError in results.TableErrors)
                    {
                        Debug.WriteLine("Error occurred when taking " + tableError.Key.TableName + " offline. Error : " + tableError.Value.Message);
                    }
                }
            }
        }
        private async Task DownloadOfflineMapArea()
        {
            var downloadTask = await OfflineMapTask.CreateAsync(TheMap.Map);

            var parameters = await downloadTask.CreateDefaultGenerateOfflineMapParametersAsync(TheMap.GetCurrentViewpoint(ViewpointType.BoundingGeometry).TargetGeometry);

            parameters.AttachmentSyncDirection     = AttachmentSyncDirection.None;
            parameters.ReturnLayerAttachmentOption = ReturnLayerAttachmentOption.None;
            var job = downloadTask.GenerateOfflineMap(parameters, OfflineMapAreaFolder);

            job.ProgressChanged += OnDemandJob_ProgressChanged;
            var result = await job.GetResultAsync();

            if (!result.HasErrors)
            {
                _offlineMapArea = result.OfflineMap;
                Device.BeginInvokeOnMainThread(() =>
                {
                    OfflineMapAreaButton.IsEnabled  = false;
                    ActivateMapAreaButton.IsEnabled = true;
                });
            }
        }
Пример #21
0
        private async void TakeMapOfflineButton_Click(object sender, EventArgs e)
        {
            // Create a path for the output mobile map.
            string tempPath = $"{Path.GetTempPath()}";

            string[] outputFolders = Directory.GetDirectories(tempPath, "NapervilleWaterNetwork*");

            // Loop through the folder names and delete them.
            foreach (string dir in outputFolders)
            {
                try
                {
                    // Delete the folder.
                    Directory.Delete(dir, true);
                }
                catch (Exception)
                {
                    // Ignore exceptions (files might be locked, for example).
                }
            }

            // Create a new folder for the output mobile map.
            string packagePath = Path.Combine(tempPath, @"NapervilleWaterNetwork");
            int    num         = 1;

            while (Directory.Exists(packagePath))
            {
                packagePath = Path.Combine(tempPath, @"NapervilleWaterNetwork" + num.ToString());
                num++;
            }

            // Create the output directory.
            Directory.CreateDirectory(packagePath);

            // Show the progress dialog while the job is running.
            _alertDialog.Show();

            // Create an offline map task with the current (online) map.
            OfflineMapTask takeMapOfflineTask = await OfflineMapTask.CreateAsync(_mapView.Map);

            // Create the default parameters for the task, pass in the area of interest.
            GenerateOfflineMapParameters parameters = await takeMapOfflineTask.CreateDefaultGenerateOfflineMapParametersAsync(_areaOfInterest);

            // Configure basemap settings for the job.
            ConfigureOfflineJobForBasemap(parameters, async() =>
            {
                try
                {
                    // Create the job with the parameters and output location.
                    _generateOfflineMapJob = takeMapOfflineTask.GenerateOfflineMap(parameters, packagePath);

                    // Handle the progress changed event for the job.
                    _generateOfflineMapJob.ProgressChanged += OfflineMapJob_ProgressChanged;

                    // Await the job to generate geodatabases, export tile packages, and create the mobile map package.
                    GenerateOfflineMapResult results = await _generateOfflineMapJob.GetResultAsync();

                    // Check for job failure (writing the output was denied, e.g.).
                    if (_generateOfflineMapJob.Status != JobStatus.Succeeded)
                    {
                        // Report failure to the user.
                        ShowStatusMessage("Failed to take the map offline.");
                    }

                    // Check for errors with individual layers.
                    if (results.LayerErrors.Any())
                    {
                        // Build a string to show all layer errors.
                        StringBuilder errorBuilder = new StringBuilder();
                        foreach (KeyValuePair <Layer, Exception> layerError in results.LayerErrors)
                        {
                            errorBuilder.AppendLine($"{layerError.Key.Id} : {layerError.Value.Message}");
                        }

                        // Show layer errors.
                        ShowStatusMessage(errorBuilder.ToString());
                    }

                    // Display the offline map.
                    _mapView.Map = results.OfflineMap;

                    // Apply the original viewpoint for the offline map.
                    _mapView.SetViewpoint(new Viewpoint(_areaOfInterest));

                    // Enable map interaction so the user can explore the offline data.
                    _mapView.InteractionOptions.IsEnabled = true;

                    // Change the title and disable the "Take map offline" button.
                    _takeMapOfflineButton.Text    = "Map is offline";
                    _takeMapOfflineButton.Enabled = false;
                }
                catch (TaskCanceledException)
                {
                    // Generate offline map task was canceled.
                    ShowStatusMessage("Taking map offline was canceled");
                }
                catch (Exception ex)
                {
                    // Exception while taking the map offline.
                    ShowStatusMessage(ex.Message);
                }
                finally
                {
                    // Hide the loading overlay when the job is done.
                    _alertDialog.Dismiss();
                }
            });
        }
        private async void Initialize()
        {
            try
            {
                // Show a loading indicator.
                View.AddSubview(_progressIndicator);
                _progressIndicator.UpdateMessageAndProgress("Loading list of available map areas.", -1);

                // Get the offline data folder.
                _offlineDataFolder = Path.Combine(GetDataFolder(),
                                                  "SampleData", "DownloadPreplannedMapAreas");

                // If the temporary data folder doesn't exist, create it.
                if (!Directory.Exists(_offlineDataFolder))
                {
                    Directory.CreateDirectory(_offlineDataFolder);
                }

                // Create a portal that contains the portal item.
                ArcGISPortal portal = await ArcGISPortal.CreateAsync();

                // Create the webmap based on the id.
                PortalItem webmapItem = await PortalItem.CreateAsync(portal, PortalItemId);

                // Create the offline map task and load it.
                _offlineMapTask = await OfflineMapTask.CreateAsync(webmapItem);

                // Query related preplanned areas.
                _preplannedMapAreas = await _offlineMapTask.GetPreplannedMapAreasAsync();

                // Load each preplanned map area.
                foreach (var area in _preplannedMapAreas)
                {
                    await area.LoadAsync();
                }

                // Show a popup menu of available areas when the download button is clicked.
                _downloadButton.TouchUpInside += (s, e) =>
                {
                    // Create the alert controller.
                    UIAlertController mapAreaSelectionAlertController = UIAlertController.Create("Map Area Selection",
                                                                                                 "Select a map area to download and show.", UIAlertControllerStyle.ActionSheet);

                    // Add one action per map area.
                    foreach (PreplannedMapArea area in _preplannedMapAreas)
                    {
                        mapAreaSelectionAlertController.AddAction(UIAlertAction.Create(area.PortalItem.Title, UIAlertActionStyle.Default,
                                                                                       action =>
                        {
                            // Download and show the selected map area.
                            OnDownloadMapAreaClicked(action.Title);
                        }));
                    }

                    // Needed to prevent a crash on iPad.
                    UIPopoverPresentationController presentationPopover = mapAreaSelectionAlertController.PopoverPresentationController;
                    if (presentationPopover != null)
                    {
                        presentationPopover.SourceView = View;
                        presentationPopover.PermittedArrowDirections = UIPopoverArrowDirection.Up;
                    }

                    // Display the alert.
                    PresentViewController(mapAreaSelectionAlertController, true, null);

                    // Remove the startup prompt if it hasn't been removed already.
                    if (_initialPrompt != null)
                    {
                        _initialPrompt.RemoveFromSuperview();
                        _initialPrompt = null;
                    }
                };

                // Remove loading indicators from UI.
                _progressIndicator.RemoveFromSuperview();
            }
            catch (Exception ex)
            {
                // Something unexpected happened, show the error message.
                UIAlertController alertController = UIAlertController.Create("An error occurred.", ex.Message, UIAlertControllerStyle.Alert);
                alertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                PresentViewController(alertController, true, null);
            }
        }
        private async void TakeMapOfflineButton_Click(object sender, EventArgs e)
        {
            // Make sure the user is logged in.

            /*
             * bool loggedIn = await EnsureLoggedInAsync();
             * if (!loggedIn)
             * {
             *  return;
             * }
             */

            // Disable the button to prevent errors.
            _takeMapOfflineButton.Enabled = false;

            // Show the loading indicator.
            _loadingIndicator.StartAnimating();

            // Create a path for the output mobile map.
            string tempPath = $"{Path.GetTempPath()}";

            string[] outputFolders = Directory.GetDirectories(tempPath, "NapervilleWaterNetwork*");

            // Loop through the folder names and delete them.
            foreach (string dir in outputFolders)
            {
                try
                {
                    // Delete the folder.
                    Directory.Delete(dir, true);
                }
                catch (Exception ex)
                {
                    // Ignore exceptions (files might be locked, for example).
                    Debug.WriteLine(ex);
                }
            }

            // Create a new folder for the output mobile map.
            string packagePath = Path.Combine(tempPath, @"NapervilleWaterNetwork");
            int    num         = 1;

            while (Directory.Exists(packagePath))
            {
                packagePath = Path.Combine(tempPath, @"NapervilleWaterNetwork" + num);
                num++;
            }

            // Create the output directory.
            Directory.CreateDirectory(packagePath);

            try
            {
                // Show the loading overlay while the job is running.
                _statusLabel.Text = "Taking map offline...";

                // Create an offline map task with the current (online) map.
                OfflineMapTask takeMapOfflineTask = await OfflineMapTask.CreateAsync(_myMapView.Map);

                // Create the default parameters for the task, pass in the area of interest.
                GenerateOfflineMapParameters parameters = await takeMapOfflineTask.CreateDefaultGenerateOfflineMapParametersAsync(_areaOfInterest);

                // Generate parameter overrides for more in-depth control of the job.
                GenerateOfflineMapParameterOverrides overrides = await takeMapOfflineTask.CreateGenerateOfflineMapParameterOverridesAsync(parameters);

                // Show the configuration window.
                ShowConfigurationWindow(overrides);

                // Finish work once the user has configured the override.
                _overridesVC.FinishedConfiguring += async() =>
                {
                    // Hide the configuration UI.
                    _overridesVC.DismissViewController(true, null);

                    // Create the job with the parameters and output location.
                    _generateOfflineMapJob = takeMapOfflineTask.GenerateOfflineMap(parameters, packagePath, overrides);

                    // Handle the progress changed event for the job.
                    _generateOfflineMapJob.ProgressChanged += OfflineMapJob_ProgressChanged;

                    // Await the job to generate geodatabases, export tile packages, and create the mobile map package.
                    GenerateOfflineMapResult results = await _generateOfflineMapJob.GetResultAsync();

                    // Check for job failure (writing the output was denied, e.g.).
                    if (_generateOfflineMapJob.Status != JobStatus.Succeeded)
                    {
                        // Report failure to the user.
                        UIAlertController messageAlert = UIAlertController.Create("Error", "Failed to take the map offline.", UIAlertControllerStyle.Alert);
                        messageAlert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                        PresentViewController(messageAlert, true, null);
                    }

                    // Check for errors with individual layers.
                    if (results.LayerErrors.Any())
                    {
                        // Build a string to show all layer errors.
                        System.Text.StringBuilder errorBuilder = new System.Text.StringBuilder();
                        foreach (KeyValuePair <Layer, Exception> layerError in results.LayerErrors)
                        {
                            errorBuilder.AppendLine($"{layerError.Key.Id} : {layerError.Value.Message}");
                        }

                        // Show layer errors.
                        UIAlertController messageAlert = UIAlertController.Create("Error", errorBuilder.ToString(), UIAlertControllerStyle.Alert);
                        messageAlert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                        PresentViewController(messageAlert, true, null);
                    }

                    // Display the offline map.
                    _myMapView.Map = results.OfflineMap;

                    // Apply the original viewpoint for the offline map.
                    _myMapView.SetViewpoint(new Viewpoint(_areaOfInterest));

                    // Enable map interaction so the user can explore the offline data.
                    _myMapView.InteractionOptions.IsEnabled = true;

                    // Change the title and disable the "Take map offline" button.
                    _statusLabel.Text             = "Map is offline";
                    _takeMapOfflineButton.Enabled = false;
                };
            }
            catch (TaskCanceledException)
            {
                // Generate offline map task was canceled.
                UIAlertController messageAlert = UIAlertController.Create("Canceled", "Taking map offline was canceled", UIAlertControllerStyle.Alert);
                messageAlert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                PresentViewController(messageAlert, true, null);
            }
            catch (Exception ex)
            {
                // Exception while taking the map offline.
                UIAlertController messageAlert = UIAlertController.Create("Error", ex.Message, UIAlertControllerStyle.Alert);
                messageAlert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                PresentViewController(messageAlert, true, null);
            }
            finally
            {
                // Hide the loading overlay when the job is done.
                _loadingIndicator.StopAnimating();
            }
        }
Пример #24
0
        /// <summary>
        /// Method that handles downloading the map into an offline map package
        /// </summary>
        private async Task DownloadPackageAsync(Envelope extent)
        {
            var syncTask = await OfflineMapTask.CreateAsync(Map);

            try
            {
                // set extent based on screen
                var parameters = await syncTask.CreateDefaultGenerateOfflineMapParametersAsync(extent);

                // set the job to generate the offline map
                GenerateOfflineMapJob = syncTask.GenerateOfflineMap(parameters, DownloadPath);

                // update the progress property when progress changes
                GenerateOfflineMapJob.ProgressChanged +=
                    (s, e) =>
                {
                    Progress = GenerateOfflineMapJob.Progress;
                };

                // listen for job changed events
                GenerateOfflineMapJob.JobChanged +=
                    async(sender, args) =>
                {
                    // If the job succeeded, check for layer and table errors
                    // if job fails, get the error
                    if (GenerateOfflineMapJob.Status == JobStatus.Succeeded)
                    {
                        var result = await GenerateOfflineMapJob.GetResultAsync();

                        // download has succeeded and there were no errors, return
                        if (result.LayerErrors.Count == 0 && result.TableErrors.Count == 0)
                        {
                            BroadcastMessenger.Instance.RaiseBroadcastMessengerValueChanged(true, BroadcastMessageKey.SyncSucceeded);
                        }
                        else
                        {
                            // if there were errors, create the error message to display to the user
                            var stringBuilder = new StringBuilder();

                            foreach (var error in result.LayerErrors)
                            {
                                stringBuilder.AppendLine(error.Value.Message);
                            }

                            foreach (var error in result.TableErrors)
                            {
                                stringBuilder.AppendLine(error.Value.Message);
                            }

                            UserPromptMessenger.Instance.RaiseMessageValueChanged(
                                Properties.Resources.GetString("DownloadWithErrors_Title"), stringBuilder.ToString()
                                , true, null);
                            BroadcastMessenger.Instance.RaiseBroadcastMessengerValueChanged(true, BroadcastMessageKey.SyncSucceeded);
                        }
                    }
                    else if (GenerateOfflineMapJob.Status == JobStatus.Failed)
                    {
                        // if the job failed but not due to user cancellation, display the error
                        if (GenerateOfflineMapJob.Error != null &&
                            GenerateOfflineMapJob.Error.Message != "User canceled: Job canceled.")
                        {
                            UserPromptMessenger.Instance.RaiseMessageValueChanged(
                                Properties.Resources.GetString("DownloadFailed_Title"), GenerateOfflineMapJob.Error.Message, true, GenerateOfflineMapJob.Error.StackTrace);
                        }
                        BroadcastMessenger.Instance.RaiseBroadcastMessengerValueChanged(false, BroadcastMessageKey.SyncSucceeded);
                    }
                };

                // begin download job
                GenerateOfflineMapJob.Start();
            }
            catch (Exception ex)
            {
                UserPromptMessenger.Instance.RaiseMessageValueChanged(
                    null, ex.Message, true, ex.StackTrace);
            }
        }
        private async void DownloadMapArea()
        {
            try
            {
                _windowService.SetBusyMessage("Downloading selected area...");
                _windowService.SetBusy(true);
                string offlineDataFolder = Path.Combine(OfflineDataStorageHelper.GetDataFolderForMap(Map));

                // If temporary data folder exists remove it
                try
                {
                    if (Directory.Exists(offlineDataFolder))
                    {
                        Directory.Delete(offlineDataFolder, true);
                    }
                }
                catch (Exception)
                {
                    // If folder can't be deleted, open a new one.
                    offlineDataFolder = Path.Combine(offlineDataFolder, DateTime.Now.Ticks.ToString());
                }

                // Step 1 Create task that is used to access map information and download areas
                var task = await OfflineMapTask.CreateAsync(Map);

                // Step 2 Create job that handles the download and provides status information
                // about the progress
                var job = task.DownloadPreplannedOfflineMap(SelectedMapArea.MapArea, offlineDataFolder);
                job.ProgressChanged += async(s, e) =>
                {
                    await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                    {
                        var generateOfflineMapJob = s as DownloadPreplannedOfflineMapJob;
                        _windowService.SetBusyMessage($"Downloading offline map... {generateOfflineMapJob.Progress}%");
                    });
                };

                // Step 3 Run the job and wait the results
                var results = await job.GetResultAsync();

                // Step 4 Check errors
                if (results.HasErrors)
                {
                    string errorString = "";
                    // If one or more layers fails, layer errors are populated with corresponding errors.
                    foreach (KeyValuePair <Layer, Exception> layerError in results.LayerErrors)
                    {
                        errorString += $"Error occurred on {layerError.Key.Name} : {layerError.Value.Message}\r\n";
                    }
                    foreach (KeyValuePair <Esri.ArcGISRuntime.Data.FeatureTable, Exception> tableError in results.TableErrors)
                    {
                        errorString += $"Error occurred on {tableError.Key.TableName} : {tableError.Value.Message}\r\n";
                    }
                    OfflineDataStorageHelper.FlushLogToDisk(errorString, Map);
                }

                // Step 5 Set offline map to use
                Map = results.OfflineMap;
                _areasOverlay.Graphics.Clear();
            }
            catch (Exception ex)
            {
                await _windowService.ShowAlertAsync(ex.Message, "Couldn't download map area");
            }
            finally
            {
                RefreshCommands();
                _windowService.SetBusy(false);
            }
        }
Пример #26
0
        private async void TakeMapOfflineButton_Click(object sender, EventArgs e)
        {
            // Make sure the user is logged in.

            /*
             * bool loggedIn = await EnsureLoggedInAsync();
             * if (!loggedIn)
             * {
             *  return;
             * }
             */

            // Disable the button to prevent errors.
            _takeMapOfflineButton.Enabled = false;

            // Show the loading indicator.
            _loadingIndicator.StartAnimating();

            // Create a path for the output mobile map.
            string tempPath = $"{Path.GetTempPath()}";

            string[] outputFolders = Directory.GetDirectories(tempPath, "NapervilleWaterNetwork*");

            // Loop through the folder names and delete them.
            foreach (string dir in outputFolders)
            {
                try
                {
                    // Delete the folder.
                    Directory.Delete(dir, true);
                }
                catch (Exception ex)
                {
                    // Ignore exceptions (files might be locked, for example).
                    Debug.WriteLine(ex);
                }
            }

            // Create a new folder for the output mobile map.
            _packagePath = Path.Combine(tempPath, @"NapervilleWaterNetwork");
            int num = 1;

            while (Directory.Exists(_packagePath))
            {
                _packagePath = Path.Combine(tempPath, @"NapervilleWaterNetwork" + num);
                num++;
            }

            // Create the output directory.
            Directory.CreateDirectory(_packagePath);

            try
            {
                // Show the loading overlay while the job is running.
                _statusLabel.Text = "Taking map offline...";

                // Create an offline map task with the current (online) map.
                _takeMapOfflineTask = await OfflineMapTask.CreateAsync(_myMapView.Map);

                // Create the default parameters for the task, pass in the area of interest.
                _parameters = await _takeMapOfflineTask.CreateDefaultGenerateOfflineMapParametersAsync(_areaOfInterest);

                // Generate parameter overrides for more in-depth control of the job.
                _overrides = await _takeMapOfflineTask.CreateGenerateOfflineMapParameterOverridesAsync(_parameters);

                // Show the configuration window.
                ShowConfigurationWindow(_overrides);

                // Finish work once the user has configured the override.
                _overridesVC.FinishedConfiguring += ConfigurationContinuation;
            }
            catch (TaskCanceledException)
            {
                // Generate offline map task was canceled.
                UIAlertController messageAlert = UIAlertController.Create("Canceled", "Taking map offline was canceled", UIAlertControllerStyle.Alert);
                messageAlert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                PresentViewController(messageAlert, true, null);
            }
            catch (Exception ex)
            {
                // Exception while taking the map offline.
                UIAlertController messageAlert = UIAlertController.Create("Error", ex.Message, UIAlertControllerStyle.Alert);
                messageAlert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                PresentViewController(messageAlert, true, null);
            }
            finally
            {
                // Hide the loading overlay when the job is done.
                _loadingIndicator.StopAnimating();
            }
        }
        private async void TakeMapOfflineButton_Click(object sender, RoutedEventArgs e)
        {
            // Create a new folder for the output mobile map.
            string packagePath = Path.Combine(Environment.ExpandEnvironmentVariables("%TEMP%"), @"NapervilleWaterNetwork");
            int    num         = 1;

            while (Directory.Exists(packagePath))
            {
                packagePath = Path.Combine(Environment.ExpandEnvironmentVariables("%TEMP%"), @"NapervilleWaterNetwork" + num.ToString());
                num++;
            }

            // Create the output directory.
            Directory.CreateDirectory(packagePath);

            try
            {
                // Show the progress indicator while the job is running.
                BusyIndicator.Visibility = Visibility.Visible;

                // Create an offline map task with the current (online) map.
                OfflineMapTask takeMapOfflineTask = await OfflineMapTask.CreateAsync(MyMapView.Map);

                // Create the default parameters for the task, pass in the area of interest.
                GenerateOfflineMapParameters parameters = await takeMapOfflineTask.CreateDefaultGenerateOfflineMapParametersAsync(_areaOfInterest);

                #region overrides

                // Generate parameter overrides for more in-depth control of the job.
                GenerateOfflineMapParameterOverrides overrides = await takeMapOfflineTask.CreateGenerateOfflineMapParameterOverridesAsync(parameters);

                // Configure the overrides using helper methods.
                ConfigureTileLayerOverrides(overrides);
                ConfigureLayerExclusion(overrides);
                CropWaterPipes(overrides);
                ApplyFeatureFilter(overrides);

                // Create the job with the parameters and output location.
                _generateOfflineMapJob = takeMapOfflineTask.GenerateOfflineMap(parameters, packagePath, overrides);

                #endregion overrides

                // Handle the progress changed event for the job.
                _generateOfflineMapJob.ProgressChanged += OfflineMapJob_ProgressChanged;

                // Await the job to generate geodatabases, export tile packages, and create the mobile map package.
                GenerateOfflineMapResult results = await _generateOfflineMapJob.GetResultAsync();

                // Check for job failure (writing the output was denied, e.g.).
                if (_generateOfflineMapJob.Status != JobStatus.Succeeded)
                {
                    MessageBox.Show("Generate offline map package failed.", "Job status");
                    BusyIndicator.Visibility = Visibility.Collapsed;
                }

                // Check for errors with individual layers.
                if (results.LayerErrors.Any())
                {
                    // Build a string to show all layer errors.
                    System.Text.StringBuilder errorBuilder = new System.Text.StringBuilder();
                    foreach (KeyValuePair <Layer, Exception> layerError in results.LayerErrors)
                    {
                        errorBuilder.AppendLine(string.Format("{0} : {1}", layerError.Key.Id, layerError.Value.Message));
                    }

                    // Show layer errors.
                    string errorText = errorBuilder.ToString();
                    MessageBox.Show(errorText, "Layer errors");
                }

                // Display the offline map.
                MyMapView.Map = results.OfflineMap;

                // Apply the original viewpoint for the offline map.
                MyMapView.SetViewpoint(new Viewpoint(_areaOfInterest));

                // Enable map interaction so the user can explore the offline data.
                MyMapView.InteractionOptions.IsEnabled = true;

                // Hide the "Take map offline" button.
                takeOfflineArea.Visibility = Visibility.Collapsed;

                // Show a message that the map is offline.
                MessageArea.Visibility = Visibility.Visible;
            }
            catch (TaskCanceledException)
            {
                // Generate offline map task was canceled.
                MessageBox.Show("Taking map offline was canceled");
            }
            catch (Exception ex)
            {
                // Exception while taking the map offline.
                MessageBox.Show(ex.Message, "Offline map error");
            }
            finally
            {
                // Hide the activity indicator when the job is done.
                BusyIndicator.Visibility = Visibility.Collapsed;
            }
        }
        private async void GeneratePreplannedMap()
        {
            ArcGISPortal portal = await ArcGISPortal.CreateAsync();

            string itemID = "a9081e4d02dc49f68c6202f03bfe302f";

            // Get a web map item using its ID.
            PortalItem webmapItem = await PortalItem.CreateAsync(portal, itemID);

            // Create a map from the web map item.
            Map onlineMap = new Map(webmapItem);

            // Create an OfflineMapTask from the map ...
            OfflineMapTask takeMapOfflineTask = await OfflineMapTask.CreateAsync(onlineMap);

            // ... or a web map portal item.
            //takeMapOfflineTask = await OfflineMapTask.CreateAsync(webmapItem);

            // Get a list of the available preplanned map areas.
            IReadOnlyList <PreplannedMapArea> preplannedMapAreaList = await takeMapOfflineTask.GetPreplannedMapAreasAsync();

            // Loop through all preplanned map areas.
            foreach (PreplannedMapArea mapArea in preplannedMapAreaList)
            {
                // Load the preplanned map area so property values can be read.
                await mapArea.LoadAsync();

                // Get the area of interest (geometry) for this area.
                Geometry aoi = mapArea.AreaOfInterest;

                // Get the portal item for this area, read the title and thumbnail image.
                PortalItem   preplannedMapItem = mapArea.PortalItem;
                string       mapTitle          = preplannedMapItem.Title;
                RuntimeImage areaThumbnail     = preplannedMapItem.Thumbnail;
            }


            PreplannedMapArea downloadMapArea = preplannedMapAreaList.First();

            string pathToOutputPackage = @"C:\LaurenCDrive\TL\Readiness\Trainings\RT_Offline_Workflows\PrePlannedMap";

            DownloadPreplannedOfflineMapJob preplannedMapJob = takeMapOfflineTask.DownloadPreplannedOfflineMap(downloadMapArea, pathToOutputPackage);

            // Generate the offline map and download it.
            DownloadPreplannedOfflineMapResult preplannedMapResult = await preplannedMapJob.GetResultAsync();

            if (!preplannedMapResult.HasErrors)
            {
                // Job completed successfully and all content was generated.
                Debug.WriteLine("Map " +
                                preplannedMapResult.MobileMapPackage.Item.Title +
                                " was saved to " +
                                preplannedMapResult.MobileMapPackage.Path);

                // Show the offline map in a MapView.
                MyMapView.Map = preplannedMapResult.OfflineMap;
            }
            else
            {
                // Job is finished but one or more layers or tables had errors.
                if (preplannedMapResult.LayerErrors.Count > 0)
                {
                    // Show layer errors.
                    foreach (var layerError in preplannedMapResult.LayerErrors)
                    {
                        Debug.WriteLine("Error occurred when taking " +
                                        layerError.Key.Name +
                                        " offline. Error : " +
                                        layerError.Value.Message);
                    }
                }
                if (preplannedMapResult.TableErrors.Count > 0)
                {
                    // Show table errors.
                    foreach (var tableError in preplannedMapResult.TableErrors)
                    {
                        Debug.WriteLine("Error occurred when taking " +
                                        tableError.Key.TableName +
                                        " offline. Error : " +
                                        tableError.Value.Message);
                    }
                }
            }
        }
Пример #29
0
        private async void TakeMapOfflineButton_Click(object sender, EventArgs e)
        {
            // Clean up any previous outputs in the temp directory.
            string tempPath = $"{Path.GetTempPath()}";

            string[] outputFolders = Directory.GetDirectories(tempPath, "NapervilleWaterNetwork*");

            // Loop through the folder names and delete them.
            foreach (string dir in outputFolders)
            {
                try
                {
                    // Delete the folder.
                    Directory.Delete(dir, true);
                }
                catch (Exception)
                {
                    // Ignore exceptions (files might be locked, for example).
                }
            }

            // Create a new folder for the output mobile map.
            string packagePath = Path.Combine(tempPath, @"NapervilleWaterNetwork");
            int    num         = 1;

            while (Directory.Exists(packagePath))
            {
                packagePath = Path.Combine(tempPath, @"NapervilleWaterNetwork" + num.ToString());
                num++;
            }

            // Create the output directory.
            Directory.CreateDirectory(packagePath);

            try
            {
                // Show the progress indicator while the job is running.
                busyIndicator.IsVisible = true;

                // Create an offline map task with the current (online) map.
                OfflineMapTask takeMapOfflineTask = await OfflineMapTask.CreateAsync(MyMapView.Map);

                // Create the default parameters for the task, pass in the area of interest.
                GenerateOfflineMapParameters parameters = await takeMapOfflineTask.CreateDefaultGenerateOfflineMapParametersAsync(_areaOfInterest);

                // Create the job with the parameters and output location.
                _generateOfflineMapJob = takeMapOfflineTask.GenerateOfflineMap(parameters, packagePath);

                // Handle the progress changed event for the job.
                _generateOfflineMapJob.ProgressChanged += OfflineMapJob_ProgressChanged;

                // Await the job to generate geodatabases, export tile packages, and create the mobile map package.
                GenerateOfflineMapResult results = await _generateOfflineMapJob.GetResultAsync();

                // Check for job failure (writing the output was denied, e.g.).
                if (_generateOfflineMapJob.Status != JobStatus.Succeeded)
                {
                    await((Page)Parent).DisplayAlert("Alert", "Generate offline map package failed.", "OK");
                    busyIndicator.IsVisible = false;
                }

                // Check for errors with individual layers.
                if (results.LayerErrors.Any())
                {
                    // Build a string to show all layer errors.
                    System.Text.StringBuilder errorBuilder = new System.Text.StringBuilder();
                    foreach (KeyValuePair <Layer, Exception> layerError in results.LayerErrors)
                    {
                        errorBuilder.AppendLine(string.Format("{0} : {1}", layerError.Key.Id, layerError.Value.Message));
                    }

                    // Show layer errors.
                    string errorText = errorBuilder.ToString();
                    await((Page)Parent).DisplayAlert("Alert", errorText, "OK");
                }

                // Display the offline map.
                MyMapView.Map = results.OfflineMap;

                // Apply the original viewpoint for the offline map.
                MyMapView.SetViewpoint(new Viewpoint(_areaOfInterest));

                // Enable map interaction so the user can explore the offline data.
                MyMapView.InteractionOptions.IsEnabled = true;

                // Hide the "Take map offline" button.
                takeOfflineArea.IsVisible = false;

                // Show a message that the map is offline.
                messageArea.IsVisible = true;
            }
            catch (TaskCanceledException)
            {
                // Generate offline map task was canceled.
                await((Page)Parent).DisplayAlert("Alert", "Taking map offline was canceled", "OK");
            }
            catch (Exception ex)
            {
                // Exception while taking the map offline.
                await((Page)Parent).DisplayAlert("Alert", ex.Message, "OK");
            }
            finally
            {
                // Hide the activity indicator when the job is done.
                busyIndicator.IsVisible = false;
            }
        }
Пример #30
0
        private async void Initialize()
        {
            try
            {
                // Show a loading indicator.
                _progressIndicator.SetTitle("Loading");
                _progressIndicator.SetMessage("Loading the available map areas.");
                _progressIndicator.SetCancelable(false);
                _progressIndicator.Show();

                // Get the offline data folder.
                _offlineDataFolder = Path.Combine(GetDataFolder(),
                                                  "SampleData", "DownloadPreplannedMapAreas");

                // If the temporary data folder doesn't exist, create it.
                if (!Directory.Exists(_offlineDataFolder))
                {
                    Directory.CreateDirectory(_offlineDataFolder);
                }

                // Create a portal that contains the portal item.
                ArcGISPortal portal = await ArcGISPortal.CreateAsync();

                // Create a webmap based on the id.
                PortalItem webmapItem = await PortalItem.CreateAsync(portal, PortalItemId);

                // Create the offline task and load it.
                _offlineMapTask = await OfflineMapTask.CreateAsync(webmapItem);

                // Query related preplanned areas.
                _preplannedMapAreas = await _offlineMapTask.GetPreplannedMapAreasAsync();

                // Load each preplanned map area.
                foreach (PreplannedMapArea area in _preplannedMapAreas)
                {
                    await area.LoadAsync();
                }

                // Show a popup menu of available areas when the download button is clicked.
                _downloadButton.Click += (s, e) =>
                {
                    // Create a menu to show the available map areas.
                    PopupMenu areaMenu = new PopupMenu(this, _downloadButton);
                    areaMenu.MenuItemClick += (sndr, evt) =>
                    {
                        // Get the name of the selected area.
                        string selectedArea = evt.Item.TitleCondensedFormatted.ToString();

                        // Download and show the map.
                        OnDownloadMapAreaClicked(selectedArea);
                    };

                    // Create the menu options.
                    foreach (PreplannedMapArea area in _preplannedMapAreas)
                    {
                        areaMenu.Menu.Add(area.PortalItem.Title.ToString());
                    }

                    // Show the menu in the view.
                    areaMenu.Show();
                };

                // Remove loading indicators from the UI.
                _progressIndicator.Dismiss();
            }
            catch (Exception ex)
            {
                // Something unexpected happened, show error message.
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.SetMessage(ex.Message).SetTitle("An error occurred").Show();
            }
        }