private async void OnDeleteAllMapAreasClicked(object sender, EventArgs e) { // Show the deletion UI. _downloadDeleteProgressDialog.SetMessage("Deleting downloaded map areas..."); _downloadDeleteProgressDialog.SetTitle("Deleting"); _downloadDeleteProgressDialog.Show(); try { // Find all downloaded offline areas from the sample folder. List <string> downloadedPackagePaths = Directory.GetDirectories(_offlineDataFolder).ToList(); foreach (string packagePath in downloadedPackagePaths) { MobileMapPackage downloadedAreaPackage = await MobileMapPackage.OpenAsync(packagePath); if (!downloadedAreaPackage.Maps.Any()) { // Delete temporary data folder from potential stray folders. Directory.Delete(_offlineDataFolder, true); } else { // Unregister all geodatabases and delete the package. await UnregisterAndRemoveMobileMapPackage(downloadedAreaPackage); } } } catch (Exception ex) { // Report the error. var builder = new AlertDialog.Builder(this); builder.SetMessage(ex.Message).SetTitle("Deleting map areas failed.").Show(); } finally { // Reset the UI. _downloadDeleteProgressDialog.Dismiss(); } }
private async void Initialize() { // Get the path to the package on disk. string filePath = DataManager.GetDataFolder("260eb6535c824209964cf281766ebe43", "SanFrancisco.mmpk"); // Open the map package. MobileMapPackage package = await OpenMobileMapPackage(filePath); // Populate the list of maps. foreach (Map map in package.Maps) { await map.LoadAsync(); _maps.Add(map); } // Show the first map by default. _myMapView.Map = _maps.First(); // Get the locator task from the package. _packageLocator = package.LocatorTask; // Create and add an overlay for showing a route. _routeOverlay = new GraphicsOverlay(); _routeOverlay.Renderer = new SimpleRenderer { Symbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, System.Drawing.Color.Blue, 3) }; _myMapView.GraphicsOverlays.Add(_routeOverlay); // Create and add an overlay for showing waypoints/stops. _waypointOverlay = new GraphicsOverlay(); _myMapView.GraphicsOverlays.Add(_waypointOverlay); // Enable tap-to-reverse geocode and tap-to-route. _myMapView.GeoViewTapped += MapView_Tapped; // Show list of maps in the UI. configureMapsButtons(); }
private async void Initialize() { // Get the path to the package on disk. string filePath = DataManager.GetDataFolder("260eb6535c824209964cf281766ebe43", "SanFrancisco.mmpk"); // Open the map package. MobileMapPackage package = await OpenMobileMapPackage(filePath); // Populate the list of maps. foreach (Map map in package.Maps) { await map.LoadAsync(); _maps.Add(map); } // Show the first map by default. _myMapView.Map = _maps.First(); // Get the locator task from the package. _packageLocator = package.LocatorTask; // Create and add an overlay for showing a route. _routeOverlay = new GraphicsOverlay(); _routeOverlay.Renderer = new SimpleRenderer { Symbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, System.Drawing.Color.Blue, 3) }; _myMapView.GraphicsOverlays.Add(_routeOverlay); // Create and add an overlay for showing waypoints/stops. _waypointOverlay = new GraphicsOverlay(); _myMapView.GraphicsOverlays.Add(_waypointOverlay); // Configure the table view for showing maps. _viewModel = new MapsViewModel(_maps); _viewModel.MapSelected += Map_Selected; _tableController = new UITableViewController(UITableViewStyle.Plain); _tableController.TableView.Source = _viewModel; }
private async void Initialize() { // Get the path to the mobile map package string filepath = GetMmpkPath(); try { // Open the map package MobileMapPackage myMapPackage = await MobileMapPackage.OpenAsync(filepath); // Check that there is at least one map if (myMapPackage.Maps.Count > 0) { // Display the first map in the package _myMapView.Map = myMapPackage.Maps.First(); } } catch (Exception e) { new AlertDialog.Builder(this).SetMessage(e.ToString()).SetTitle("Error").Show(); } }
private async void Initialize() { // Get the path to the mobile map package. string filepath = DataManager.GetDataFolder("e1f3a7254cb845b09450f54937c16061", "Yellowstone.mmpk"); try { // Load directly or unpack then load as needed by the map package. if (await MobileMapPackage.IsDirectReadSupportedAsync(filepath)) { // Open the map package. MobileMapPackage myMapPackage = await MobileMapPackage.OpenAsync(filepath); // Display the first map in the package. _myMapView.Map = myMapPackage.Maps.First(); } else { // Create a path for the unpacked package. string unpackedPath = filepath + "unpacked"; // Unpack the package. await MobileMapPackage.UnpackAsync(filepath, unpackedPath); // Open the package. MobileMapPackage package = await MobileMapPackage.OpenAsync(unpackedPath); // Load the package. await package.LoadAsync(); // Show the first map. _myMapView.Map = package.Maps.First(); } } catch (Exception e) { new UIAlertView("Error", e.ToString(), (IUIAlertViewDelegate)null, "OK", null).Show(); } }
private async void Initialize() { // Get the path to the mobile map package. string filepath = GetMmpkPath(); try { // Load directly or unpack then load as needed by the map package. if (await MobileMapPackage.IsDirectReadSupportedAsync(filepath)) { // Open the map package. MobileMapPackage myMapPackage = await MobileMapPackage.OpenAsync(filepath); // Display the first map in the package. _myMapView.Map = myMapPackage.Maps.First(); } else { // Create a path for the unpacked package. string unpackedPath = filepath + "unpacked"; // Unpack the package. await MobileMapPackage.UnpackAsync(filepath, unpackedPath); // Open the package. MobileMapPackage package = await MobileMapPackage.OpenAsync(unpackedPath); // Load the package. await package.LoadAsync(); // Show the first map. _myMapView.Map = package.Maps.First(); } } catch (Exception e) { new AlertDialog.Builder(this).SetMessage(e.ToString()).SetTitle("Error").Show(); } }
private async void Initialize() { // Get the path to the mobile map package. string filepath = GetMmpkPath(); try { // Load directly or unpack then load as needed by the map package. if (await MobileMapPackage.IsDirectReadSupportedAsync(filepath)) { // Open the map package. MobileMapPackage myMapPackage = await MobileMapPackage.OpenAsync(filepath); // Display the first map in the package. MyMapView.Map = myMapPackage.Maps.First(); } else { // Create a path for the unpacked package. string unpackedPath = filepath + "unpacked"; // Unpack the package. await MobileMapPackage.UnpackAsync(filepath, unpackedPath); // Open the package. MobileMapPackage package = await MobileMapPackage.OpenAsync(unpackedPath); // Load the package. await package.LoadAsync(); // Show the first map. MyMapView.Map = package.Maps.First(); } } catch (Exception e) { await((Page)Parent).DisplayAlert("Error", e.ToString(), "OK"); } }
private async void Initialize() { try { // Clear the exiting sample data. Directory.Delete(DataManager.GetDataFolder(_itemId, ""), true); } catch (IOException) { // Do nothing. Exception happens when sample hasn't been run before and data isn't already present. } try { // Download the mobile map package using the sample viewer's data manager. await DataManager.DownloadDataItem(_itemId); // Get the folder path to the mobile map package. _mapPackagePath = DataManager.GetDataFolder(_itemId, ""); // Load the mobile map package. _mobileMapPackage = new MobileMapPackage(_mapPackagePath); await _mobileMapPackage.LoadAsync(); // Set the mapview to the map from the package. Map offlineMap = _mobileMapPackage.Maps[0]; _myMapView.Map = offlineMap; // Create an offline map sync task for the map. _offlineMapSyncTask = await OfflineMapSyncTask.CreateAsync(offlineMap); // Check if there are scheduled updates to the preplanned map area. CheckForScheduledUpdates(); } catch (Exception ex) { new UIAlertView("Error", ex.Message, (IUIAlertViewDelegate)null, "OK", null).Show(); } }
private async void Initialize() { // Get the path to the mobile map package string filepath = GetMmpkPath(); try { // Open the map package MobileMapPackage myMapPackage = await MobileMapPackage.OpenAsync(filepath); // Check that there is at least one map if (myMapPackage.Maps.Count > 0) { // Display the first map in the package MyMapView.Map = myMapPackage.Maps.First(); } } catch (Exception e) { await((Page)Parent).DisplayAlert("Error", e.ToString(), "OK"); } }
private async void Initialize() { // Get the path to the mobile map package. string filepath = DataManager.GetDataFolder("e1f3a7254cb845b09450f54937c16061", "Yellowstone.mmpk"); try { // Open the map package. MobileMapPackage myMapPackage = await MobileMapPackage.OpenAsync(filepath); // Check that there is at least one map. if (myMapPackage.Maps.Count > 0) { // Display the first map in the package. _myMapView.Map = myMapPackage.Maps.First(); } } catch (Exception e) { new UIAlertView("Error", e.ToString(), (IUIAlertViewDelegate)null, "OK", null).Show(); } }
/// <summary> /// CHargement du package de carte et de la carte asociée. /// </summary> async private void LoadMapPackage() { // ouverture du Map mobile package var mapPackage = await MobileMapPackage.OpenAsync(@".\Data\DemoParis2.mmpk"); // récupération de la première carte var map = mapPackage.Maps[0]; // On assigne notre map à la vue, la carte se charge. mapView1.Map = map; if (mapPackage.Locator != null) { // assignation de l'event clic sur la carte mapView1.GeoViewTapped += mapView1_GeoViewTapped; // recupere le locator du package myLocator = mapPackage.Locator; } }
private async void ActivateButton_Clicked(object sender, EventArgs e) { // Open the map package. MobileMapPackage myMapPackage = await MobileMapPackage.OpenAsync(GetMmpkPath()); await myMapPackage.LoadAsync(); // Get our annotation layer var annoLayer = myMapPackage.Maps.First().AllLayers.First(); myMapPackage.Maps.First().OperationalLayers.Clear(); myMapPackage.Close(); // Add it to our offline map area _offlineMapArea.OperationalLayers.Add(annoLayer); TheMap.Map = _offlineMapArea; Device.BeginInvokeOnMainThread(() => { ActivateMapAreaButton.IsEnabled = false; UpdateFeatureButton.IsEnabled = true; }); }
private async void Initialize() { //Exercise 1: Create new Map with basemap and initial location myMap = new Map(Basemap.CreateNationalGeographic()); //Exercise 1: Assign the map to the MapView mapView.Map = myMap; //Exercise 3: Add mobile map package to the map var mmpk = await MobileMapPackage.OpenAsync(MMPK_PATH); if (mmpk.Maps.Count >= 0) { myMap = mmpk.Maps[0]; //Exercise 3: Mobile map package does not contain a basemap so must add one. myMap.Basemap = Basemap.CreateNationalGeographic(); mapView.Map = myMap; } mapView.GraphicsOverlays.Add(bufferAndQueryMapGraphics); mapView.GraphicsOverlays.Add(mapRouteGraphics); Uri routeServiceUri = new Uri("http://route.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World"); TokenCredential credentials = await AuthenticationManager.Current.GenerateCredentialAsync(routeServiceUri, "username", "password"); routeTask = await RouteTask.CreateAsync(routeServiceUri, credentials); try { routeParameters = await routeTask.GenerateDefaultParametersAsync(); } catch (Exception error) { Console.WriteLine(error.Message); } }
private async Task CheckPreplannedMap() { if (!Directory.Exists(PreplannedDataFolder)) { Directory.CreateDirectory(PreplannedDataFolder); } if (Directory.EnumerateFiles(PreplannedDataFolder).Any()) { try { var mmpk = await MobileMapPackage.OpenAsync(PreplannedDataFolder); PreplannedStatusLabel.Text = "Preplanned Map: Download complete."; PreplannedStatusLabel.TextColor = Color.Green; _preplannedMap = mmpk.Maps.First(); } catch (Exception) { Directory.Delete(PreplannedDataFolder, true); await CheckPreplannedMap(); } } }
/// <summary> /// /// </summary> /// <param name="map"></param> /// <param name="viewpoint"></param> /// <param name="jobHandler"></param> /// <param name="progressHandler"></param> /// <returns></returns> public async Task <DownloadReplicaResult> DownloadReplicaAsync(Map map, Viewpoint viewpoint, EventHandler <JobChangedEventArgs> jobHandler, EventHandler <ProgressChangedEventArgs> progressHandler) { ValidateReplicaFolderPath(); var pathToOutputPackage = GetReplicaFullPath(); var areaOfInterest = viewpoint.TargetGeometry; var task = await OfflineMapTask.CreateAsync(map); var parameters = await task.CreateDefaultGenerateOfflineMapParametersAsync(areaOfInterest); parameters.MinScale = MinScale; parameters.MaxScale = MaxScale; parameters.AttachmentSyncDirection = AttachmentSyncDirection.Bidirectional; parameters.ReturnLayerAttachmentOption = ReturnLayerAttachmentOption.AllLayers; parameters.ReturnSchemaOnlyForEditableLayers = false; parameters.ItemInfo.Title = $"{parameters.ItemInfo.Title} (Off-line)"; var errors = new List <DownloadReplicaErrorResult>(); var capabilitiesResults = await task.GetOfflineMapCapabilitiesAsync(parameters); if (capabilitiesResults.HasErrors) { errors.AddRange(capabilitiesResults.LayerCapabilities.ToList() .Where(l => !l.Value.SupportsOffline || l.Value.Error != null) .Select(l => new DownloadReplicaErrorResult { Name = l.Key.Name, SupportOffline = l.Value.SupportsOffline, Error = l.Value.Error })); errors.AddRange(capabilitiesResults.TableCapabilities.ToList() .Where(t => !t.Value.SupportsOffline || t.Value.Error != null) .Select(t => new DownloadReplicaErrorResult { Name = t.Key.TableName, SupportOffline = t.Value.SupportsOffline, Error = t.Value.Error })); return(new DownloadReplicaResult { ResultErrors = errors }); } else { var job = task.GenerateOfflineMap(parameters, pathToOutputPackage); if (jobHandler != null) { JobChangedEventHandler += jobHandler; job.JobChanged += (o, e) => { JobChangedEventHandler?.Invoke(job, new JobChangedEventArgs() { Messages = job.Messages, Status = job.Status }); }; } if (progressHandler != null) { ProgressChangedEventHandler += progressHandler; job.ProgressChanged += (o, e) => { ProgressChangedEventHandler?.Invoke(job, new ProgressChangedEventArgs() { Progress = job.Progress }); }; } var generateOfflineMapResults = await job.GetResultAsync(); if (!generateOfflineMapResults.HasErrors) { var okMessage = $"{AppResources.DownloadReplicaOkMessageMap} " + $"{generateOfflineMapResults.MobileMapPackage.Item.Title} " + $"{AppResources.DownloadReplicaOkMessageSaved}."; MobileMapPackage = generateOfflineMapResults.MobileMapPackage; return(new DownloadReplicaResult { Map = generateOfflineMapResults.OfflineMap, MapTitle = okMessage }); } else { errors.AddRange(generateOfflineMapResults.LayerErrors.ToList() .Select(l => new DownloadReplicaErrorResult { Name = l.Key.Name, Message = l.Value.Message })); errors.AddRange(generateOfflineMapResults.TableErrors.ToList() .Select(t => new DownloadReplicaErrorResult { Name = t.Key.TableName, Message = t.Value.Message })); return(new DownloadReplicaResult { ResultErrors = errors }); } } }
private async void DownloadMapAreaAsync(PreplannedMapArea mapArea) { // Close the current mobile package. _mobileMapPackage?.Close(); // Set up UI for downloading. _activityIndicator.StartAnimating(); _helpLabel.Text = "Downloading map area..."; // Create folder path where the map package will be downloaded. string path = Path.Combine(_offlineDataFolder, mapArea.PortalItem.Title); // If the area is already downloaded, open it. if (Directory.Exists(path)) { try { _mobileMapPackage = await MobileMapPackage.OpenAsync(path); _myMapView.Map = _mobileMapPackage.Maps.First(); _helpLabel.Text = "Opened offline area."; _showOnlineButton.Enabled = true; _activityIndicator.StopAnimating(); return; } catch (Exception e) { Debug.WriteLine(e); new UIAlertView("Couldn't open offline map area. Proceeding to take area offline.", e.ToString(), (IUIAlertViewDelegate)null, "OK", null).Show(); } } // Create download parameters. DownloadPreplannedOfflineMapParameters parameters = await _offlineMapTask.CreateDefaultDownloadPreplannedOfflineMapParametersAsync(mapArea); // Set the update mode to not receive updates. parameters.UpdateMode = PreplannedUpdateMode.NoUpdates; // Create the job. DownloadPreplannedOfflineMapJob job = _offlineMapTask.DownloadPreplannedOfflineMap(parameters, path); // Set up event to update the progress bar while the job is in progress. job.ProgressChanged += Job_ProgressChanged; try { // Download the area. DownloadPreplannedOfflineMapResult results = await job.GetResultAsync(); // Set the current mobile map package. _mobileMapPackage = results.MobileMapPackage; // Handle possible errors and show them to the user. if (results.HasErrors) { // Accumulate all layer and table errors into a single message. string errors = ""; foreach (KeyValuePair <Layer, Exception> layerError in results.LayerErrors) { errors = $"{errors}\n{layerError.Key.Name} {layerError.Value.Message}"; } foreach (KeyValuePair <FeatureTable, Exception> tableError in results.TableErrors) { errors = $"{errors}\n{tableError.Key.TableName} {tableError.Value.Message}"; } // Show the message. new UIAlertView("Warning!", errors, (IUIAlertViewDelegate)null, "OK", null).Show(); } // Show the downloaded map. _myMapView.Map = results.OfflineMap; } catch (Exception ex) { // Report any errors. Debug.WriteLine(ex); new UIAlertView("Downloading map area failed", ex.ToString(), (IUIAlertViewDelegate)null, "OK", null).Show(); } finally { _activityIndicator.StopAnimating(); _helpLabel.Text = "Map area offline."; _showOnlineButton.Enabled = true; } }
private async Task DownloadMapAreaAsync(PreplannedMapArea mapArea) { // Configure UI for the download. DownloadNotificationText.Visibility = Visibility.Collapsed; ProgressBar.IsIndeterminate = false; ProgressBar.Value = 0; BusyText.Text = "Downloading map area..."; BusyIndicator.Visibility = Visibility.Visible; MyMapView.Visibility = Visibility.Visible; // Get the path for the downloaded map area. string path = Path.Combine(_offlineDataFolder, mapArea.PortalItem.Title); // If the area is already downloaded, open it and don't download it again. if (Directory.Exists(path)) { MobileMapPackage localMapArea = await MobileMapPackage.OpenAsync(path); try { // Load the map. MyMapView.Map = localMapArea.Maps.First(); // Update the UI. BusyText.Text = string.Empty; BusyIndicator.Visibility = Visibility.Collapsed; // Return and don't proceed to download. return; } catch (Exception) { // Do nothing, continue as if map wasn't downloaded. } } // Create job that is used to download the map area. DownloadPreplannedOfflineMapJob job = _offlineMapTask.DownloadPreplannedOfflineMap(mapArea, path); // Subscribe to progress change events to support showing a progress bar. job.ProgressChanged += OnJobProgressChanged; try { // Download the map area. DownloadPreplannedOfflineMapResult results = await job.GetResultAsync(); // Handle possible errors and show them to the user. if (results.HasErrors) { StringBuilder errorBuilder = new StringBuilder(); // Add layer errors to the message. foreach (KeyValuePair <Layer, Exception> layerError in results.LayerErrors) { errorBuilder.AppendLine(string.Format("{0} {1}", layerError.Key.Name, layerError.Value.Message)); } // Add table errors to the message. foreach (KeyValuePair <FeatureTable, Exception> tableError in results.TableErrors) { errorBuilder.AppendLine(string.Format("{0} {1}", tableError.Key.TableName, tableError.Value.Message)); } // Show the message. MessageDialog message = new MessageDialog(errorBuilder.ToString(), "Warning!"); await message.ShowAsync(); } // Show the Map in the MapView. MyMapView.Map = results.OfflineMap; } catch (Exception ex) { // Report exception. MessageDialog message = new MessageDialog(ex.Message, "Downloading map areas failed"); await message.ShowAsync(); } finally { // Clear the loading UI. BusyText.Text = string.Empty; BusyIndicator.Visibility = Visibility.Collapsed; } }
private async Task DownloadMapAreaAsync(PreplannedMapArea mapArea) { // Set up UI for downloading. ProgressBar.IsIndeterminate = false; ProgressBar.Value = 0; BusyText.Text = "Downloading map area..."; BusyIndicator.Visibility = Visibility.Visible; // Create folder path where the map package will be downloaded. string path = Path.Combine(_offlineDataFolder, mapArea.PortalItem.Title); // If the area is already downloaded, open it. if (Directory.Exists(path)) { try { // Open the offline map package. MobileMapPackage localMapArea = await MobileMapPackage.OpenAsync(path); // Display the first map. MyMapView.Map = localMapArea.Maps.First(); // Update the UI. BusyText.Text = string.Empty; BusyIndicator.Visibility = Visibility.Collapsed; MessageLabel.Text = "Opened offline area."; return; } catch (Exception e) { Debug.WriteLine(e); await new MessageDialog(e.Message, "Couldn't open offline area. Proceeding to take area offline.").ShowAsync(); } } // Create download parameters. DownloadPreplannedOfflineMapParameters parameters = await _offlineMapTask.CreateDefaultDownloadPreplannedOfflineMapParametersAsync(mapArea); // Create the job. DownloadPreplannedOfflineMapJob job = _offlineMapTask.DownloadPreplannedOfflineMap(parameters, path); // Set up event to update the progress bar while the job is in progress. job.ProgressChanged += OnJobProgressChanged; try { // Download the area. DownloadPreplannedOfflineMapResult results = await job.GetResultAsync(); // Handle possible errors and show them to the user. if (results.HasErrors) { // Accumulate all layer and table errors into a single message. string errors = ""; foreach (KeyValuePair <Layer, Exception> layerError in results.LayerErrors) { errors = $"{errors}\n{layerError.Key.Name} {layerError.Value.Message}"; } foreach (KeyValuePair <FeatureTable, Exception> tableError in results.TableErrors) { errors = $"{errors}\n{tableError.Key.TableName} {tableError.Value.Message}"; } // Show the message. await new MessageDialog(errors, "Warning!").ShowAsync(); } // Show the downloaded map. MyMapView.Map = results.OfflineMap; // Update the UI. MessageLabel.Text = "Downloaded preplanned area."; } catch (Exception ex) { // Report any errors. Debug.WriteLine(ex); await new MessageDialog(ex.Message, "Downloading map area failed.").ShowAsync(); } finally { BusyText.Text = string.Empty; BusyIndicator.Visibility = Visibility.Collapsed; } }
private async Task DownloadMapAreaAsync(PreplannedMapArea mapArea) { // Show the download UI. _progressIndicator.UpdateMessageAndProgress("Downloading map area", 0); View.AddSubview(_progressIndicator); // Get the path for the downloaded map area. var path = Path.Combine(_offlineDataFolder, mapArea.PortalItem.Title); // If the area is already downloaded, open it and don't download it again. if (Directory.Exists(path)) { var localMapArea = await MobileMapPackage.OpenAsync(path); try { // Load the map. _myMapView.Map = localMapArea.Maps.First(); // Reset the UI. _progressIndicator.RemoveFromSuperview(); // Return without proceeding to download. return; } catch (Exception) { // Do nothing, continue as if map wasn't downloaded. } } // Create the job that is used to do the download. DownloadPreplannedOfflineMapJob job = _offlineMapTask.DownloadPreplannedOfflineMap(mapArea, path); // Subscribe to progress change events to support showing a progress bar. job.ProgressChanged += OnJobProgressChanged; try { // Download the map area. DownloadPreplannedOfflineMapResult results = await job.GetResultAsync(); // Handle possible errors and show them to the user. if (results.HasErrors) { var errorBuilder = new StringBuilder(); // Add layer errors to the message. foreach (KeyValuePair <Layer, Exception> layerError in results.LayerErrors) { errorBuilder.AppendLine($"{layerError.Key.Name} {layerError.Value.Message}"); } // Add table errors to the message. foreach (KeyValuePair <FeatureTable, Exception> tableError in results.TableErrors) { errorBuilder.AppendLine($"{tableError.Key.TableName} {tableError.Value.Message}"); } // Show the message. UIAlertController alertController = UIAlertController.Create("Warning!", errorBuilder.ToString(), UIAlertControllerStyle.Alert); alertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); PresentViewController(alertController, true, null); } // Show the Map in the MapView. _myMapView.Map = results.OfflineMap; } catch (Exception ex) { // Report the exception. UIAlertController alertController = UIAlertController.Create("Downloading map area failed.", ex.Message, UIAlertControllerStyle.Alert); alertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); PresentViewController(alertController, true, null); } finally { // Clear the loading UI. _progressIndicator.RemoveFromSuperview(); } }
private async Task DownloadMapAreaAsync(PreplannedMapArea mapArea) { // Set up UI for download. _progressIndicator.SetMessage("Downloading map area..."); _progressIndicator.SetTitle("Downloading"); _progressIndicator.Show(); // Get the path for the downloaded map area. string path = Path.Combine(_offlineDataFolder, mapArea.PortalItem.Title); // If the map area is already downloaded, open it and don't download it again. if (Directory.Exists(path)) { MobileMapPackage localMapArea = await MobileMapPackage.OpenAsync(path); try { // Load the map area. _myMapView.Map = localMapArea.Maps.First(); // Update the UI. _progressIndicator.Dismiss(); // Return without downloading the item again. return; } catch (Exception) { // Do nothing, continue as if the map wasn't downloaded. } } // Create the job that is used to download the map area. DownloadPreplannedOfflineMapJob job = _offlineMapTask.DownloadPreplannedOfflineMap(mapArea, path); // Subscribe to progress change events to support showing a progress bar. job.ProgressChanged += OnJobProgressChanged; try { // Download the map area. DownloadPreplannedOfflineMapResult results = await job.GetResultAsync(); // Handle possible errors and show them to the user. if (results.HasErrors) { StringBuilder errorBuilder = new StringBuilder(); // Add layer errors to the message. foreach (KeyValuePair <Layer, Exception> layerError in results.LayerErrors) { errorBuilder.AppendLine($"{layerError.Key.Name} {layerError.Value.Message}"); } // Add table errors to the message. foreach (KeyValuePair <FeatureTable, Exception> tableError in results.TableErrors) { errorBuilder.AppendLine($"{tableError.Key.TableName} {tableError.Value.Message}"); } // Show the error message. AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.SetMessage(errorBuilder.ToString()).SetTitle("Warning!").Show(); } // Show the Map in the MapView. _myMapView.Map = results.OfflineMap; } catch (Exception ex) { // Report exception. AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.SetMessage(ex.Message).SetTitle("Downloading map area failed.").Show(); } finally { // Clear the loading UI. _progressIndicator.Dismiss(); } }
private async void GenerateOnDemand() { ArcGISPortal portal = await ArcGISPortal.CreateAsync(); // Get a web map item using its ID. PortalItem webmapItem = await PortalItem.CreateAsync(portal, "dba73588a56d476484b8d0fa1c480c9b"); // 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); await onlineMap.LoadAsync(); // Create default parameters for the task. Envelope areaOfInterest = GetAreaOfInterest(); GenerateOfflineMapParameters parameters = await takeMapOfflineTask.CreateDefaultGenerateOfflineMapParametersAsync(areaOfInterest); // Limit the maximum scale to 5000 but take all the scales above (use default of 0 as the MinScale). parameters.MaxScale = 5000; // Set attachment options. parameters.AttachmentSyncDirection = AttachmentSyncDirection.Upload; parameters.ReturnLayerAttachmentOption = ReturnLayerAttachmentOption.EditableLayers; // Request the table schema only (existing features won’t be included). parameters.ReturnSchemaOnlyForEditableLayers = true; // Update the map title to contain the region. parameters.ItemInfo.Title = parameters.ItemInfo.Title + " (Central)"; // Override the thumbnail with a new image based on the extent. RuntimeImage thumbnail = await MyMapView.ExportImageAsync(); parameters.ItemInfo.Thumbnail = thumbnail; // Create the job to generate an offline map, pass in the parameters and a path to store the map package. GenerateOfflineMapJob generateMapJob = takeMapOfflineTask.GenerateOfflineMap(parameters, pathToOutputPackage); // 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); // Show the offline map in a MapView. MyMapView.Map = offlineMapResult.OfflineMap; } 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); } } } OfflineMapCapabilities results = await takeMapOfflineTask.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!"); } // Create a mobile map package from an unpacked map package folder. MobileMapPackage offlineMapPackage = await MobileMapPackage.OpenAsync(pathToOutputPackage); // Set the title from the package metadata to the UI // Get the map from the package and set it to the MapView var map = offlineMapPackage.Maps.First(); MyMapView.Map = map; }
private async Task DownloadMapAreaAsync(PreplannedMapArea mapArea) { // Close the current mobile package. _mobileMapPackage?.Close(); // Set up UI for downloading. ProgressView.Progress = 0; BusyText.Text = "Downloading map area..."; BusyIndicator.IsVisible = true; // Create folder path where the map package will be downloaded. string path = Path.Combine(_offlineDataFolder, mapArea.PortalItem.Title); // If the area is already downloaded, open it. if (Directory.Exists(path)) { try { // Open the offline map package. _mobileMapPackage = await MobileMapPackage.OpenAsync(path); // Open the first map in the package. MyMapView.Map = _mobileMapPackage.Maps.First(); // Update the UI. BusyText.Text = string.Empty; BusyIndicator.IsVisible = false; MessageLabel.Text = "Opened offline area."; return; } catch (Exception e) { Debug.WriteLine(e); await Application.Current.MainPage.DisplayAlert("Couldn't open offline area. Proceeding to take area offline.", e.Message, "OK"); } } // Create download parameters. DownloadPreplannedOfflineMapParameters parameters = await _offlineMapTask.CreateDefaultDownloadPreplannedOfflineMapParametersAsync(mapArea); // Set the update mode to not receive updates. parameters.UpdateMode = PreplannedUpdateMode.NoUpdates; // Create the job. DownloadPreplannedOfflineMapJob job = _offlineMapTask.DownloadPreplannedOfflineMap(parameters, path); // Set up event to update the progress bar while the job is in progress. job.ProgressChanged += OnJobProgressChanged; try { // Download the area. DownloadPreplannedOfflineMapResult results = await job.GetResultAsync(); // Set the current mobile map package. _mobileMapPackage = results.MobileMapPackage; // Handle possible errors and show them to the user. if (results.HasErrors) { // Accumulate all layer and table errors into a single message. string errors = ""; foreach (KeyValuePair <Layer, Exception> layerError in results.LayerErrors) { errors = $"{errors}\n{layerError.Key.Name} {layerError.Value.Message}"; } foreach (KeyValuePair <FeatureTable, Exception> tableError in results.TableErrors) { errors = $"{errors}\n{tableError.Key.TableName} {tableError.Value.Message}"; } // Show the message. await Application.Current.MainPage.DisplayAlert("Warning!", errors, "OK"); } // Show the downloaded map. MyMapView.Map = results.OfflineMap; // Update the UI. ShowOnlineButton.IsEnabled = true; MessageLabel.Text = "Downloaded preplanned area."; DownloadButton.Text = "Display"; } catch (Exception ex) { // Report any errors. Debug.WriteLine(ex); await Application.Current.MainPage.DisplayAlert("Downloading map area failed.", ex.Message, "OK"); } finally { BusyText.Text = string.Empty; BusyIndicator.IsVisible = false; } }
private async Task DownloadMapAreaAsync(PreplannedMapArea mapArea) { // Show the UI for the download. ProgressBar.Progress = 0; BusyText.Text = "Downloading map area..."; BusyIndicator.IsVisible = true; MyMapView.IsVisible = true; // Get the path for the downloaded map area. string path = Path.Combine(_offlineDataFolder, mapArea.PortalItem.Title); // If the area is already downloaded, open it and don't download it again. if (Directory.Exists(path)) { MobileMapPackage localMapArea = await MobileMapPackage.OpenAsync(path); try { // Load the map. MyMapView.Map = localMapArea.Maps.First(); // Update the UI. BusyText.Text = string.Empty; BusyIndicator.IsVisible = false; // Return without proceeding to download. return; } catch (Exception) { // Do nothing, continue as if the map wasn't downloaded. } } // Create the job that is used to do the download. DownloadPreplannedOfflineMapJob job = _offlineMapTask.DownloadPreplannedOfflineMap(mapArea, path); // Subscribe to progress change events to support showing a progress bar. job.ProgressChanged += OnJobProgressChanged; try { // Download the map area. DownloadPreplannedOfflineMapResult results = await job.GetResultAsync(); // Handle possible errors and show them to the user. if (results.HasErrors) { StringBuilder errorBuilder = new StringBuilder(); // Add layer errors to the message. foreach (KeyValuePair <Layer, Exception> layerError in results.LayerErrors) { errorBuilder.AppendLine($"{layerError.Key.Name} {layerError.Value.Message}"); } // Add table errors to the message. foreach (KeyValuePair <FeatureTable, Exception> tableError in results.TableErrors) { errorBuilder.AppendLine($"{tableError.Key.TableName} {tableError.Value.Message}"); } // Show the message. await((Page)Parent).DisplayAlert("Warning!", errorBuilder.ToString(), "OK"); } // Show the Map in the MapView. MyMapView.Map = results.OfflineMap; } catch (Exception ex) { // Report the exception. await((Page)Parent).DisplayAlert("Downloading map area failed.", ex.Message, "OK"); } finally { // Clear the loading UI. BusyText.Text = string.Empty; BusyIndicator.IsVisible = false; } }
/// <summary> /// Defines the method to be called when the command is invoked. /// </summary> /// <param name="parameter">Data used by the command. If the command does not require data to be passed, this object can be set to null.</param> public void Execute(object parameter) { // We expect the parameter to be an ESRI MapView. var mapView = parameter as MapView; // Let the user find a mobile map package file. var ofd = new OpenFileDialog(); ofd.Filter = "Mobile map package files (*.mmpk)|*.mmpk|All files (*.*)|*.*"; // If the user opens the if (ofd.ShowDialog() == true) { try { // Load the mobile map package. var mobileMapPackage = Task.Run(async() => { /** * If you're looking for a place to put a breakpoint to * witness the loading of the Mobile Map Package, * here's a good place to start. */ return(await MobileMapPackage.OpenAsync(ofd.FileName)); }).Result; #region If there are no maps in the map package... if (mobileMapPackage.Maps.Count == 0) { MessageBox.Show( "The map package contains no maps.", "No Maps", MessageBoxButton.OK, MessageBoxImage.Error); return; } #endregion // If that worked, we can update the map view model with // the new mobile map package. MapViewModel.Current.MobileMapPackage = mobileMapPackage; // Update the map view with the first map in the mobile map // package. var map = mobileMapPackage.Maps[0]; MapViewModel.Current.MapView.Map = map; #region The tool doesn't need to execute again. if (this.CanExecuteChanged != null) { this.CanExecuteChanged(this, new EventArgs()); } #endregion #region Report the success. MessageBox.Show( "The map is loaded.\r\nClick to perform reverse geocodes.", "Good to Go", MessageBoxButton.OK, MessageBoxImage.Information); return; #endregion } catch (Exception ex) { #region Let's tell the user what happened... MessageBox.Show( string.Format("Can't open '{0}': {1}", ofd.FileName, ex.Message), ex.GetType().Name, MessageBoxButton.OK, MessageBoxImage.Error); throw; #endregion } } }