protected async override void OnElementChanged(ElementChangedEventArgs <Page> e) { // Call the method on the base base.OnElementChanged(e); // Exit if the element (Page) is null if (e.OldElement != null || Element == null) { return; } // Set up the AuthenticationManager to challenge for ArcGIS Online credentials UpdateAuthenticationManager(); // Force an OAuth challenge CredentialRequestInfo info = new CredentialRequestInfo { AuthenticationType = AuthenticationType.Token, ServiceUri = new Uri(OAuthPage.PortalUrl) }; await AuthenticationManager.Current.GetCredentialAsync(info, false); // Open the desired web map (portal item) ArcGISPortal portal = await ArcGISPortal.CreateAsync(new Uri(OAuthPage.PortalUrl)); PortalItem item = await PortalItem.CreateAsync(portal, OAuthPage.WebMapId); // Create a map Map myMap = new Map(item); // Set the MyMap property on the shared form to display the map in the map view var oauthPage = e.NewElement as OAuthPage; oauthPage.MyMap = myMap; }
private async void OpenFeaturesFromArcGISOnline(string itemId) { try { // Open a portal item containing a feature collection ArcGISPortal portal = await ArcGISPortal.CreateAsync(); PortalItem collectionItem = await PortalItem.CreateAsync(portal, itemId); // Verify that the item is a feature collection if (collectionItem.Type == PortalItemType.FeatureCollection) { // Create a new FeatureCollection from the item FeatureCollection featCollection = new FeatureCollection(collectionItem); // Create a layer to display the collection and add it to the map as an operational layer FeatureCollectionLayer featCollectionLayer = new FeatureCollectionLayer(featCollection); featCollectionLayer.Name = collectionItem.Title; MyMapView.Map.OperationalLayers.Add(featCollectionLayer); } else { MessageBox.Show("Portal item with ID '" + itemId + "' is not a feature collection.", "Feature Collection"); } } catch (Exception ex) { MessageBox.Show("Unable to open item with ID '" + itemId + "': " + ex.Message, "Error"); } }
public static async Task <WebMap> GetMapAsync(string mapId) { if (string.IsNullOrWhiteSpace(mapId)) { throw new ArgumentException("mapUrl is required"); } ArcGISPortal arcGISOnline = await ArcGISPortal.CreateAsync(); var portalItem = await PortalItem.CreateAsync(arcGISOnline, mapId); //Could not get this to work as expected //await DownloadMapAsync(portalItem); // load the model var model = new WebMap() { Id = mapId, Title = portalItem.Title, Snippet = portalItem.Snippet, Thumbnail = new BitmapImage(portalItem.ThumbnailUri) }; return(model); }
public static async Task DownloadItem(string itemId) { var portal = await ArcGISPortal.CreateAsync().ConfigureAwait(false); var item = await PortalItem.CreateAsync(portal, itemId).ConfigureAwait(false); string dataDir = Path.Combine(GetDataFolder(itemId)); if (!Directory.Exists(dataDir)) { Directory.CreateDirectory(dataDir); } Task <Stream> downloadTask = item.GetDataAsync(); string tempFile = Path.Combine(dataDir, item.Name); using (var s = await downloadTask.ConfigureAwait(false)) { using (var f = File.Create(tempFile)) { await s.CopyToAsync(f).ConfigureAwait(false); } } if (tempFile.EndsWith(".zip")) { await UnpackData(tempFile, dataDir); } string configFilePath = Path.Combine(dataDir, "__sample.config"); File.WriteAllText(configFilePath, @"Data downloaded: " + DateTime.Now); }
private async Task <PortalItem> GetPortalItemAsync(string portalUrl, string itemId, string username, string password) { var key = $"{portalUrl};{username}"; var portal = _portalConnections.ContainsKey(key) ? _portalConnections[key] : null; PortalItem item; // Connect to Portal var portalUri = new Uri(PortalUrlBox.Text); if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password)) { // Authenticate and then connect if user and password are specified var cred = await AuthenticationManager.Current.GenerateCredentialAsync(portalUri, username, password); portal = await ArcGISPortal.CreateAsync(portalUri, cred); } else { // Connect anonymously if user and/or password aren't specified portal = await ArcGISPortal.CreateAsync(portalUri); } _portalConnections[key] = portal; // Get the item for the specified ID item = await PortalItem.CreateAsync(portal, itemId); return(item); }
private async void Initialize() { // Create a portal and an item; the map will be loaded from portal item. ArcGISPortal portal = await ArcGISPortal.CreateAsync(new Uri("https://runtime.maps.arcgis.com")); PortalItem mapItem = await PortalItem.CreateAsync(portal, "3953413f3bd34e53a42bf70f2937a408"); // Create the map from the item. Map webMap = new Map(mapItem); // Update the UI when the map navigates. _myMapView.ViewpointChanged += (o, e) => _scaleLabel.Text = $"Current map scale: 1:{_myMapView.MapScale:n0}"; // Display the map. _myMapView.Map = webMap; // Wait for the map to load. await webMap.LoadAsync(); // Configure the tableview controller to enable managing layers. _layerTableController = new UITableViewController(); _layerTableController.TableView.Source = new LayerViewModel(webMap); // Enable the button now that the map is ready. _layerSelectionButton.Enabled = true; }
private async void OpenFeaturesFromArcGISOnline(string itemId) { try { // Open a portal item containing a feature collection. ArcGISPortal portal = await ArcGISPortal.CreateAsync(); PortalItem collectionItem = await PortalItem.CreateAsync(portal, itemId); // Verify that the item is a feature collection. if (collectionItem.Type == PortalItemType.FeatureCollection) { // Create a new FeatureCollection from the item. FeatureCollection featureCollection = new FeatureCollection(collectionItem); // Create a layer to display the collection and add it to the map as an operational layer. FeatureCollectionLayer featureCollectionLayer = new FeatureCollectionLayer(featureCollection) { Name = collectionItem.Title }; _myMapView.Map.OperationalLayers.Add(featureCollectionLayer); } else { var alert = new UIAlertView("Feature Collection", "Portal item with ID '" + itemId + "' is not a feature collection.", (IUIAlertViewDelegate)null, "OK"); alert.Show(); } } catch (Exception ex) { var alert = new UIAlertView("Error", "Unable to open item with ID '" + itemId + "': " + ex.Message, (IUIAlertViewDelegate)null, "OK"); alert.Show(); } }
private async void OpenFeaturesFromArcGISOnline(string collectionItemId) { try { // Create a portal item PortalItem collectionItem = await PortalItem.CreateAsync(_portal, collectionItemId); // Verify that the item is a feature collection and add to the map if (collectionItem.Type == PortalItemType.FeatureCollection) { // Create a new FeatureCollection from the item _featCollection = new FeatureCollection(collectionItem); // Create a layer to display the collection and add it to the map as an operational layer _featCollectionLayer = new FeatureCollectionLayer(_featCollection); // Add the feature collection layer to the map MyMapView.Map.OperationalLayers.Add(_featCollectionLayer); } else { MessageBox.Show("Portal item with ID '" + collectionItemId + "' is not a feature collection.", "Feature Collection"); } } catch (Exception ex) { MessageBox.Show("Unable to open item with ID '" + collectionItemId + "': " + ex.Message, "Error"); } }
private async void Initialize() { try { // Create the portal item from the URL to the webmap. PortalItem alaskaPortalItem = await PortalItem.CreateAsync(_mapUri); // Create the map from the portal item. Map myMap = new Map(alaskaPortalItem); // Add the map to the mapview. _myMapView.Map = myMap; // Wait for the map to load. await myMap.LoadAsync(); // Get the feature layer from the map. _myFeatureLayer = (FeatureLayer)myMap.OperationalLayers.First(); // Update the selection color. _myMapView.SelectionProperties.Color = Color.Yellow; } catch (Exception e) { new UIAlertView("Error", e.ToString(), (IUIAlertViewDelegate)null, "OK", null).Show(); } }
public async Task <Map> GetMap() { if (_config.usetileCache) { var imageryTiledLayer = new ArcGISTiledLayer(new Uri(_config.basemap)); Map map = new Map(); map.Basemap = new Basemap(imageryTiledLayer); return(map); } try { var Portal = await ArcGISPortal.CreateAsync(new Uri(_config.webMap.url)); PortalItem webMapItem = null; webMapItem = await PortalItem.CreateAsync(Portal, _config.webMap.item); Map map = new Map(webMapItem); return(map); } catch (Exception ex) { throw new Exception($"Kan ikke laste kart; Portal inneholder ikke WebMap med Id {_config.webMap.item}: {ex.Message}"); } }
private async Task Initialize() { try { // Set the map var portal = await ArcGISPortal.CreateAsync(); var item = await PortalItem.CreateAsync(portal, "fc76be1ab8a049edb4e659c1837bcca4"); var map = new Map(item); TheMap.Map = map; // Copy our annotation layer mmpk into place for loading later using (var resource = Assembly.GetExecutingAssembly().GetManifestResourceStream("mmpk_annotation_layer_issue.simple_anno_mmpk.mmpk")) { using (var file = new FileStream(GetMmpkPath(), FileMode.Create, FileAccess.Write)) { resource.CopyTo(file); } } } catch (Exception e) { await Application.Current.MainPage.DisplayAlert("Error", e.ToString(), "OK"); } }
private async void Initialize() { try { // Create the portal item from the URL to the webmap PortalItem alaskaPortalItem = await PortalItem.CreateAsync(_mapUri); // Create the map from the portal item Map myMap = new Map(alaskaPortalItem); // Add the map to the mapview MyMapView.Map = myMap; // Wait for the map to load await myMap.LoadAsync(); // Get the feature layer from the map _myFeatureLayer = (FeatureLayer)myMap.OperationalLayers.First(); // Make the selection color yellow. MyMapView.SelectionProperties.Color = Colors.Yellow; // Listen for GeoViewTapped events MyMapView.GeoViewTapped += MyMapViewOnGeoViewTapped; } catch (Exception e) { await Application.Current.MainPage.DisplayAlert("Error", e.ToString(), "OK"); } }
private async void MyMapView_Loaded(object sender, RoutedEventArgs e) { //住所検索用のジオコーディング タスクを初期化 onlineLocatorTask = await LocatorTask.CreateAsync(new Uri(WORLD_GEOCODE_SERVICE_URL)); //ArcGIS Online への参照を取得 ArcGISPortal arcGISOnline = await ArcGISPortal.CreateAsync(new Uri(PORTAL_URL)); // ID を基にアイテムを取得 var portalItem = await PortalItem.CreateAsync(arcGISOnline, "Web マップ ID"); //アイテムから Map オブジェクトを作成 var Map = new Map(portalItem); //MapView コントロールの Map プロパティに、Map を割り当て MyMapView.Map = Map; // グラフィックス オーバーレイが存在しない場合は、新規に追加 if (MyMapView.GraphicsOverlays.Count == 0) { geocodeResultGraphicsOverlay = new GraphicsOverlay() { Renderer = CreateGeocoordingSymbol(), }; MyMapView.GraphicsOverlays.Add(geocodeResultGraphicsOverlay); } isMapReady = true; }
private async void Initialize() { // Create the portal item from the URL to the webmap. PortalItem alaskaPortalItem = await PortalItem.CreateAsync(_mapUri); // Create the map from the portal item. Map myMap = new Map(alaskaPortalItem); // Add the map to the mapview. MyMapView.Map = myMap; // Wait for the map to load. await myMap.LoadAsync(); // Get the feature layer from the map. _myFeatureLayer = (FeatureLayer)myMap.OperationalLayers.First(); // Wait for the layer to load. await _myFeatureLayer.LoadAsync(); // Make the selection color yellow and the width thick. _myFeatureLayer.SelectionColor = Color.Yellow; _myFeatureLayer.SelectionWidth = 5; // Listen for GeoViewTapped events. MyMapView.GeoViewTapped += MyMapViewOnGeoViewTapped; // Hide the loading indicator. LoadingProgress.Visibility = Visibility.Collapsed; }
private async void DisplaySecureMap() { // Display a web map hosted in a portal. If the web map item is secured, AuthenticationManager will // challenge for credentials try { // ... code here to license the app immediately and/or save the license (JSON string) to take the app offline ... // License the app using the license info // Connect to a portal (ArcGIS Online, for example) ArcGISPortal arcgisPortal = await ArcGISPortal.CreateAsync(new Uri(ServerUrl)); Esri.ArcGISRuntime.ArcGISRuntimeEnvironment.SetLicense(arcgisPortal.PortalInfo.LicenseInfo); // Get a web map portal item using its ID // If the item is secured (not shared publicly) the user will be challenged for credentials at this point PortalItem portalItem = await PortalItem.CreateAsync(arcgisPortal, WebMapId); // Create a new map with the portal item Map myMap = new Map(portalItem); // Assign the map to the MapView.Map property to display it in the app MyMapView.Map = myMap; await myMap.RetryLoadAsync(); } catch (Exception ex) { MessageBox.Show("Error displaying map: " + ex.Message); } }
private async void DisplayWebMap() { // Display a web map hosted in a portal. If the web map item is secured, AuthenticationManager will // challenge for credentials try { // Connect to a portal (ArcGIS Online, for example) ArcGISPortal arcgisPortal = await ArcGISPortal.CreateAsync(new Uri(ServerUrl)); // Get a web map portal item using its ID // If the item is secured (not shared publicly) the user will be challenged for credentials at this point PortalItem portalItem = await PortalItem.CreateAsync(arcgisPortal, WebMapId); // Create a new map with the portal item Map myMap = new Map(portalItem); // Assign the map to the MapView.Map property to display it in the app MyMapView.Map = myMap; await myMap.RetryLoadAsync(); } catch (Exception ex) { MessageDialog dlg = new MessageDialog(ex.Message); await dlg.ShowAsync(); } }
private async void Initialize() { try { // Create the portal item from the URL to the webmap PortalItem alaskaPortalItem = await PortalItem.CreateAsync(_mapUri); // Create the map from the portal item Map myMap = new Map(alaskaPortalItem); // Add the map to the mapview _myMapView.Map = myMap; // Wait for the map to load await myMap.LoadAsync(); // Get the feature layer from the map _myFeatureLayer = (FeatureLayer)myMap.OperationalLayers.First(); // Update the selection color _myMapView.SelectionProperties.Color = Color.Yellow; // Listen for GeoViewTapped events _myMapView.GeoViewTapped += MyMapViewOnGeoViewTapped; } catch (Exception e) { new AlertDialog.Builder(this).SetMessage(e.ToString()).SetTitle("Error").Show(); } }
/// <summary> /// Ensures that data needed for a sample has been downloaded and is up-to-date. /// </summary> /// <param name="sample">The sample to ensure data is present for.</param> public static async Task EnsureSampleDataPresent(SampleInfo sample, CancellationToken token) { // Return if there's nothing to do. if (sample.OfflineDataItems == null || !sample.OfflineDataItems.Any()) { return; } // Hold a list of download tasks (to enable parallel download). List <Task> downloads = new List <Task>(); foreach (string itemId in sample.OfflineDataItems) { // Create ArcGIS portal item var portal = await ArcGISPortal.CreateAsync(token).ConfigureAwait(false); var item = await PortalItem.CreateAsync(portal, itemId, token).ConfigureAwait(false); // Download item if not already present if (!IsDataPresent(item)) { Task downloadTask = DownloadItem(item, token); downloads.Add(downloadTask); } } // Wait for all downloads to complete await Task.WhenAll(downloads).WithCancellation(token); }
private async Task InitializeOnlineMap() { var portal = await ArcGISPortal.CreateAsync(); var item = await PortalItem.CreateAsync(portal, "a5283e945e69456e9a4d1d29a0e0796e"); TheMap.Map = new Map(item); }
private async void AddMapItem_Click(object sender, RoutedEventArgs e) { // Get a web map from the selected portal item and display it in the app if (MapItemListBox.SelectedItem == null) { return; } // Clear status messages MessagesTextBlock.Text = string.Empty; var messageBuilder = new StringBuilder(); try { // See if this is the public or secured portal and get the appropriate object reference ArcGISPortal portal = null; if (_usingPublicPortal) { portal = _publicPortal; } else { portal = _pkiSecuredPortal; } // Throw an exception if the portal is null if (portal == null) { throw new Exception("Portal has not been instantiated."); } // Get the portal item ID from the selected list box item (read it from the Tag property) var itemId = (MapItemListBox.SelectedItem as ListBoxItem).Tag.ToString(); // Use the item ID to create an ArcGISPortalItem from the appropriate portal var portalItem = await PortalItem.CreateAsync(portal, itemId); // Create a Map from the portal item (all items in the list represent web maps) var webMap = new Map(portalItem); // Display the Map in the map view MyMapView.Map = webMap; // Report success messageBuilder.AppendLine("Successfully loaded web map from item #" + itemId + " from " + portal.Uri.Host); } catch (Exception ex) { // Add an error message messageBuilder.AppendLine("Error accessing web map: " + ex.Message); } finally { // Show messages MessagesTextBlock.Text = messageBuilder.ToString(); } }
// Connect to the portal identified by the SecuredPortalUrl variable and load the web map identified by WebMapId private async void LoadSecureMap(object s, EventArgs e) { // Store messages that describe success or errors connecting to the secured portal and opening the web map var messageBuilder = new System.Text.StringBuilder(); try { // See if a credential exists for this portal in the AuthenticationManager // If a credential is not found, the user will be prompted for login info CredentialRequestInfo info = new CredentialRequestInfo { ServiceUri = new Uri(SecuredPortalUrl), AuthenticationType = AuthenticationType.NetworkCredential }; Credential cred = await AuthenticationManager.Current.GetCredentialAsync(info, false); // Create an instance of the IWA-secured portal ArcGISPortal iwaSecuredPortal = await ArcGISPortal.CreateAsync(new Uri(SecuredPortalUrl)); // Report a successful connection messageBuilder.AppendLine("Connected to the portal on " + iwaSecuredPortal.Uri.Host); messageBuilder.AppendLine("Version: " + iwaSecuredPortal.CurrentVersion); // Report the username for this connection if (iwaSecuredPortal.CurrentUser != null) { messageBuilder.AppendLine("Connected as: " + iwaSecuredPortal.CurrentUser.UserName); } else { // This shouldn't happen (if the portal is truly secured)! messageBuilder.AppendLine("Connected anonymously"); } // Get the web map (portal item) to display var webMap = await PortalItem.CreateAsync(iwaSecuredPortal, WebMapId); if (webMap != null) { // Create a new map from the portal item and display it in the map view var map = new Map(webMap); _myMapView.Map = map; } } catch (Exception ex) { // Report error messageBuilder.AppendLine("**-Exception: " + ex.Message); } finally { // Show an alert dialog with the status messages var alertBuilder = new AlertDialog.Builder(this); alertBuilder.SetTitle("Status"); alertBuilder.SetMessage(messageBuilder.ToString()); alertBuilder.Show(); } }
private async void CreateOnlineMap() { // Load map from a portal item ArcGISPortal portal = await ArcGISPortal.CreateAsync(); webmapItem = await PortalItem.CreateAsync(portal, "acc027394bc84c2fb04d1ed317aac674"); // Create map and add it to the view MyMapView.Map = new Map(webmapItem); }
/// <summary> /// Gets the data for the map. It downloads the mmpk if it doesn't exist or if there's a newer one available /// </summary> /// <returns>The map data.</returns> public async Task GetDataAsync() { // List of all files inside the Documents directory on the device this.Files = Directory.EnumerateFiles(GetDataFolder()).ToList(); this.TargetFileName = Path.Combine(GetDataFolder(), AppSettings.CurrentSettings.PortalItemName); // Test if device is online // If offline, test if mmpk exists and load it // If offline and no mmpk, show error // Show error message if unable to downoad the mmpk. This is usually when the device is online but signal isn't strong enough and connection to Portal times out if (IsDeviceConnected()) { try { // Get portal item var portal = await ArcGISPortal.CreateAsync().ConfigureAwait(false); var item = await PortalItem.CreateAsync(portal, AppSettings.CurrentSettings.PortalItemID).ConfigureAwait(false); // Test if mmpk is not already downloaded or is older than current portal version if (!this.Files.Contains(this.TargetFileName) || item.Modified.LocalDateTime > AppSettings.CurrentSettings.MmpkDownloadDate) { this.IsDownloading = true; this.DownloadURL = item.Url.AbsoluteUri + "/data"; } else { this.IsReady = true; } } catch (Exception ex) { // If unable to get item from Portal, use already existing map package, unless this is the initial application download. if (this.Files.Contains(this.TargetFileName)) { this.IsReady = true; } else { this.Status = ex.Message; this.IsDownloading = false; } } } else if (this.Files.Contains(this.TargetFileName)) { this.IsReady = true; } else { this.IsDownloading = false; this.Status = "Device does not seem to be connected to the network and the necessary data has not been downloaded. Please retry when in network range"; } }
private async void OnLoadMapClicked(object sender, EventArgs e) { // Challenge the user for portal credentials CredentialRequestInfo loginInfo = new CredentialRequestInfo(); // Use the OAuth implicit grant flow loginInfo.GenerateTokenOptions = new GenerateTokenOptions { TokenAuthenticationType = TokenAuthenticationType.OAuthImplicit }; // Indicate the url (portal) to authenticate with loginInfo.ServiceUri = new Uri(PortalUrl); try { // Get a reference to the (singleton) AuthenticationManager for the app AuthenticationManager thisAuthenticationManager = AuthenticationManager.Current; // Call GetCredentialAsync on the AuthenticationManager to invoke the challenge handler await thisAuthenticationManager.GetCredentialAsync(loginInfo, false); // Access the portal ArcGISPortal portal = await ArcGISPortal.CreateAsync(new Uri(PortalUrl)); // Get the item (web map) from the portal PortalItem item = await PortalItem.CreateAsync(portal, WebMapId); // Make sure it's a web map if (item.Type != PortalItemType.WebMap) { return; } // Display the web map in the map view Map webMap = new Map(item); _myMapView.Map = webMap; } catch (System.OperationCanceledException) { // User canceled the login var alertBuilder = new AlertDialog.Builder(this); alertBuilder.SetTitle("Cancel"); alertBuilder.SetMessage("Portal login was canceled."); alertBuilder.Show(); } catch (Exception ex) { // Other exception var alertBuilder = new AlertDialog.Builder(this); alertBuilder.SetTitle("Error"); alertBuilder.SetMessage(ex.Message); alertBuilder.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(); } }
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(); } }
public static async Task EnsureDataPresent() { var portal = await ArcGISPortal.CreateAsync(); var item = await PortalItem.CreateAsync(portal, SampleDataId); if (!IsDataPresent(item)) { // We download the latest data from using the ArcGIS portal await DownloadData(item); } }
private async Task LoadItemsAsync(ArcGISPortal portal) { try { var waterHydrantInspectionsItemId = "c9fbe40a90a7474988bbba12fe7de04d"; WaterHydrantInspectionsItem = await PortalItem.CreateAsync(portal, waterHydrantInspectionsItemId); } catch (Exception) { throw; } }
/// <summary> /// Downloads data from ArcGIS Portal and unzips it to the local data folder /// </summary> /// <param name="path">The path to put the data in - if the folder already exists, the data is assumed to have been downloaded and this immediately returns</param> /// <returns></returns> public static async Task GetData(string itemId, string sampleName) { // Method for creating directories as needed Action <DirectoryInfo> createDir = null; createDir = (s) => { System.Diagnostics.Debug.WriteLine(s.FullName); if (Directory.Exists(s.FullName)) { return; } if (!Directory.Exists(s.Parent.FullName)) { createDir(s.Parent); } Directory.CreateDirectory(s.FullName); }; // Create the portal var portal = await ArcGISPortal.CreateAsync().ConfigureAwait(false); // Create the portal item var item = await PortalItem.CreateAsync(portal, itemId).ConfigureAwait(false); // Create the SampleData folder var tempFile = Path.Combine(GetDataFolder(), "SampleData"); createDir(new DirectoryInfo(tempFile)); // Create the sample-specific folder tempFile = Path.Combine(tempFile, sampleName); createDir(new DirectoryInfo(tempFile)); // Get the full path to the specific file tempFile = Path.Combine(tempFile, item.Name); // Download the file using (var s = await item.GetDataAsync().ConfigureAwait(false)) { using (var f = File.Create(tempFile)) { await s.CopyToAsync(f).ConfigureAwait(false); } } // Unzip the file if it is a zip file if (tempFile.EndsWith(".zip")) { await UnpackData(tempFile, Path.Combine(GetDataFolder(), "SampleData", sampleName)); } }
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(); } }