private async Task GetMyMaps() { // Call a sub that will force the user to log in to ArcGIS Online (if they haven't already). bool loggedIn = await EnsureLoggedInAsync(); if (!loggedIn) { return; } // Connect to the portal (will connect using the provided credentials). var portal = await ArcGISPortal.CreateAsync(new Uri(ServerUrl)); // Get the user's content (items in the root folder and a collection of sub-folders). PortalUserContent myContent = await portal.User.GetContentAsync(); // Get the web map items in the root folder. IEnumerable <PortalItem> mapItems = from item in myContent.Items where item.Type == PortalItemType.WebMap select item; // Loop through all sub-folders and get web map items, add them to the mapItems collection. foreach (PortalFolder folder in myContent.Folders) { IEnumerable <PortalItem> folderItems = await portal.User.GetContentAsync(folder.FolderId); mapItems = mapItems.Concat(from item in folderItems where item.Type == PortalItemType.WebMap select item); } // Show the map results. ShowMapList(mapItems); }
private static void OnPortalChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { ArcGISPortalServiceSearchProvider provider = (ArcGISPortalServiceSearchProvider)d; ArcGISPortal oldPortal = e.OldValue as ArcGISPortal; ArcGISPortal newPortal = e.NewValue as ArcGISPortal; // Unhook from old portal if (oldPortal != null) { oldPortal.PropertyChanged -= provider.Portal_PropertyChanged; } if (newPortal != null) { // Initialize display name if portal is initialized. Otherwise, listen for property changes // and wait for portal initialization. if (newPortal.IsInitialized && !provider.isDisplayNameInitialized()) { provider.initDisplayName(); } else if (!newPortal.IsInitialized) { newPortal.PropertyChanged += provider.Portal_PropertyChanged; } } provider.OnPropertyChanged("Portal"); }
private async void SearchPublicMaps(string searchText) { try { // Get web map portal items from a keyword search IEnumerable <PortalItem> mapItems; // Connect to the portal (anonymously) ArcGISPortal portal = await ArcGISPortal.CreateAsync(new Uri(ArcGISOnlineUrl)); // Create a query expression that will get public items of type 'web map' with the keyword(s) in the items tags string queryExpression = $"tags:\"{searchText}\" access:public type: (\"web map\" NOT \"web mapping application\")"; // Create a query parameters object with the expression and a limit of 10 results PortalQueryParameters queryParams = new PortalQueryParameters(queryExpression, 10); // Search the portal using the query parameters and await the results PortalQueryResultSet <PortalItem> findResult = await portal.FindItemsAsync(queryParams); // Get the items from the query results mapItems = findResult.Results; // Hide the search controls SearchMapsUI.IsVisible = false; // Show the list of web maps MapsListView.ItemsSource = mapItems.ToList(); // Explicit ToList() needed to avoid Xamarin.Forms UWP ListView bug. MapsListView.IsVisible = true; } catch (Exception e) { await Application.Current.MainPage.DisplayAlert("Error", e.ToString(), "OK"); } }
// Search the IWA-secured portal for web maps and display the results in a list. private async void SearchSecureMapsButtonClick(object sender, RoutedEventArgs e) { try { // Get the string entered for the secure portal URL. string securedPortalUrl = SecurePortalUrlTextBox.Text.Trim(); // Make sure a portal URL has been entered in the text box. if (string.IsNullOrEmpty(securedPortalUrl)) { MessageBox.Show("Please enter the URL of the secured portal.", "Missing URL"); return; } // Check if the current Window credentials should be used or require an explicit login. bool requireLogin = RequireLoginCheckBox.IsChecked == true; // Create an instance of the IWA-secured portal, the user may be challenged for access. _iwaSecuredPortal = await ArcGISPortal.CreateAsync(new Uri(securedPortalUrl), requireLogin); // Call a function to search the portal. SearchPortal(_iwaSecuredPortal); // Set a variable that indicates this is the secure portal. // When a map is loaded from the results, will need to know which portal it came from. _usingPublicPortal = false; } catch (Exception ex) { // Report errors (connecting to the secured portal, for example). MessagesTextBlock.Text = ex.Message; } }
/// <summary> /// Gets a collection of web map items from ArcGIS Online /// </summary> /// <returns></returns> private async Task <List <WebMapItem> > GetWebMapsAsync() { var lstWebmapItems = new List <WebMapItem>(); try { await QueuedTask.Run(async() => { ArcGISPortal portal = ArcGISPortalManager.Current.GetPortal(new Uri(_arcgisOnline)); PortalQueryParameters query = PortalQueryParameters.CreateForItemsOfType(PortalItemType.WebMap); PortalQueryResultSet <PortalItem> results = await ArcGIS.Desktop.Core.ArcGISPortalExtensions.SearchForContentAsync(portal, query); if (results == null) { return; } foreach (var item in results.Results.OfType <PortalItem>()) { lstWebmapItems.Add(new WebMapItem(item)); } }); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } return(lstWebmapItems); }
public async Task AttemptAnonymousAccessAsync() { var challengeHandler = IdentityManager.Current.ChallengeHandler; // Deactivate the challenge handler temporarily before creating the portal (else challengehandler would be called for portal secured by native) IdentityManager.Current.ChallengeHandler = new ChallengeHandler(crd => null); try { var p = await ArcGISPortal.CreateAsync(App.PortalUri.Uri); if (p != null) { //set the ArcGISPortal Portal = p; SetOrganizationProperties(); GalaSoft.MvvmLight.Messaging.Messenger.Default.Send <ArcGISPortalViewer.Helpers.ChangedPortalServiceMessage>(new ArcGISPortalViewer.Helpers.ChangedPortalServiceMessage()); } } catch (Exception ex) { throw new Exception(ex.Message); } finally { // Restore ChallengeHandler IdentityManager.Current.ChallengeHandler = challengeHandler; } }
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 { await((Page)Parent).DisplayAlert("Feature Collection", "Portal item with ID '" + itemId + "' is not a feature collection.", "OK"); } } catch (Exception ex) { await((Page)Parent).DisplayAlert("Error", "Unable to open item with ID '" + itemId + "': " + ex.Message, "OK"); } }
// Loads the given webmap private async Task LoadWebMapAsync(ArcGISPortalItem portalItem) { try { IsBusy = true; if (_portal == null) { _portal = await ArcGISPortal.CreateAsync(); } var webmap = await WebMap.FromPortalItemAsync(portalItem); LoadedPortalItem = portalItem; CurrentWebMapVM = await WebMapViewModel.LoadAsync(webmap, _portal); } catch (Exception ex) { var _ = new MessageDialog(ex.Message, "Sample Error").ShowAsync(); } finally { IsBusy = false; } }
private async Task LoadMaps(ArcGISPortal portal) { StatusMessage = "Loading maps..."; var task1 = portal.ArcGISPortalInfo.SearchBasemapGalleryAsync(); var task2 = portal.ArcGISPortalInfo.SearchFeaturedItemsAsync(new SearchParameters("") { Limit = 50 }); var items = await task1; Basemaps = items.Results; var groups = new ObservableCollection <MapGroup>(); Groups = groups; groups.Add(new MapGroup() { Name = "Base maps", Items = Basemaps }); IsLoadingBasemaps = false; StatusMessage = string.Format("Connected to {0} ({1})", portal.ArcGISPortalInfo.PortalName, portal.ArcGISPortalInfo.PortalHostname); items = await task2; Featured = items.Results; groups.Add(new MapGroup() { Name = "Featured", Items = Featured }); Groups = groups; }
// Initialize the display with a web map and search portal for basemaps private async void control_Loaded(object sender, RoutedEventArgs e) { _portal = await ArcGISPortal.CreateAsync(); // Initial search on load DoSearch(); }
private void LoadPortalBasemaps() { // Initialize a portal to get the query to return web maps in the basemap gallery ArcGISPortal portal = new ArcGISPortal(); portal.InitializeAsync("http://www.arcgis.com/sharing/rest", (s, e) => { if (portal.ArcGISPortalInfo != null) { // Return the first 20 basemaps in the gallery SearchParameters parameters = new SearchParameters() { Limit = 20 }; // Use the advertised query to search the basemap gallery and return web maps as portal items portal.ArcGISPortalInfo.SearchBasemapGalleryAsync(parameters, (result, error) => { if (error == null && result != null) { basemapList.ItemsSource = result.Results; } }); } }); }
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; }
// Loads UI elements and an initial webmap private async void LoadWebMap_Loaded(object sender, RoutedEventArgs e) { _portal = await ArcGISPortal.CreateAsync(); var searchParams = new SearchParameters("type: \"web map\" NOT \"web mapping application\""); var result = await _portal.ArcGISPortalInfo.SearchHomePageFeaturedContentAsync(searchParams); comboWebMap.ItemsSource = result.Results; }
private async Task SaveNewMapAsync(Map myMap, string title, string description, string[] tags, RuntimeImage img) { // Challenge the user for portal credentials (OAuth credential request for arcgis.com) CredentialRequestInfo loginInfo = new CredentialRequestInfo(); // Use the OAuth implicit grant flow loginInfo.GenerateTokenOptions = new GenerateTokenOptions { TokenAuthenticationType = TokenAuthenticationType.OAuthImplicit }; // Indicate the url (portal) to authenticate with (ArcGIS Online) loginInfo.ServiceUri = new Uri("https://www.arcgis.com/sharing/rest"); 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); } catch (System.OperationCanceledException) { // user canceled the login throw new Exception("Portal log in was canceled."); } // Get the ArcGIS Online portal (will use credential from login above) ArcGISPortal agsOnline = await ArcGISPortal.CreateAsync(); // Save the current state of the map as a portal item in the user's default folder await myMap.SaveAsAsync(agsOnline, null, title, description, tags, img); }
/// <summary> /// Signs user into Portal and updates the AuthenticatedUser property /// </summary> private async Task <Credential> SignIntoPortal() { try { // IOAuthAuthorizeHandler will challenge the user for OAuth credentials var credential = await AuthenticationManager.Current.GenerateCredentialAsync(new Uri(Configuration.ArcGISOnlineUrl)); AuthenticationManager.Current.AddCredential(credential); // Create connection to Portal and provide credential var portal = await ArcGISPortal.CreateAsync(new Uri(Configuration.ArcGISOnlineUrl), credential); AuthenticatedUser = portal.User; return(credential); } catch (System.OperationCanceledException) { // User cancelled login return(null); } catch (Exception ex) { ErrorMessage = string.Format("Authentication failed"); StackTrace = ex.ToString(); return(null); } }
/// <summary> /// Search the IWA-secured portal for web maps and display the results in a list box. /// </summary> private async void SearchSecureMapsButton_Click(object sender, RoutedEventArgs e) { // Set the flag variable to indicate we're working with the secure portal // (if the user wants to load a map, we'll need to know which portal it came from) _usingPublicPortal = false; MapItemListBox.Items.Clear(); // Show status message and the status bar MessagesTextBlock.Text = "Searching for web map items on the secure portal."; ProgressStatus.Visibility = Windows.UI.Xaml.Visibility.Visible; var sb = new StringBuilder(); try { // Create an instance of the IWA-secured portal _iwaSecuredPortal = await ArcGISPortal.CreateAsync(new Uri(SecuredPortalUrl)); // Report a successful connection sb.AppendLine("Connected to the portal on " + _iwaSecuredPortal.Uri.Host); sb.AppendLine("Version: " + _iwaSecuredPortal.CurrentVersion); // Report the username used for this connection if (_iwaSecuredPortal.CurrentUser != null) { sb.AppendLine("Connected as: " + _iwaSecuredPortal.CurrentUser.UserName); } else { sb.AppendLine("Anonymous"); // THIS SHOULDN'T HAPPEN! } // Search the secured portal for web maps var items = await _iwaSecuredPortal.SearchItemsAsync(new SearchParameters("type:(\"web map\" NOT \"web mapping application\")")); // Build a list of items from the results that shows the map title and stores the item ID (with the Tag property) var resultItems = from r in items.Results select new ListBoxItem { Tag = r.Id, Content = r.Title }; // Add the list items foreach (var itm in resultItems) { MapItemListBox.Items.Add(itm); } } catch (TaskCanceledException tce) { sb.AppendLine(tce.Message); } catch (Exception ex) { // Report errors connecting to or searching the secured portal sb.AppendLine(ex.Message); } finally { // Show messages, hide progress bar MessagesTextBlock.Text = sb.ToString(); ProgressStatus.Visibility = Windows.UI.Xaml.Visibility.Collapsed; } }
// Handle the SearchTextEntered event from the search input UI. // SearchMapsEventArgs contains the search text that was entered. private async void SearchTextEntered(string searchText) { try { // Connect to the portal (anonymously). ArcGISPortal portal = await ArcGISPortal.CreateAsync(new Uri(ServerUrl)); // Create a query expression that will get public items of type 'web map' with the keyword(s) in the items tags. string queryExpression = $"tags:\"{searchText}\" access:public type: (\"web map\" NOT \"web mapping application\")"; // Create a query parameters object with the expression and a limit of 10 results. PortalQueryParameters queryParams = new PortalQueryParameters(queryExpression, 10); // Search the portal using the query parameters and await the results. PortalQueryResultSet <PortalItem> findResult = await portal.FindItemsAsync(queryParams); // Get the items from the query results. IEnumerable <PortalItem> mapItems = findResult.Results; // Show the map results. ShowMapList(mapItems); } catch (Exception ex) { // Report search error. UIAlertController alert = UIAlertController.Create("Error", ex.Message, UIAlertControllerStyle.Alert); alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); PresentViewController(alert, true, null); } }
private async void LoadWebMap() { try { ArcGISPortal portal = new ArcGISPortal() { Url = "http://www.arcgis.com/sharing/rest" }; ArcGISPortalItem portalItem = new ArcGISPortalItem(portal) { Id = "00e5e70929e14055ab686df16c842ec1" }; WebMap webMap = await WebMap.FromPortalItemTaskAsync(portalItem); MyWebMapViewModel = await WebMapViewModel.LoadAsync(webMap, portalItem.ArcGISPortal); } catch (Exception ex) { if (ex is ServiceException) { MessageBox.Show(String.Format("{0}: {1}", (ex as ServiceException).Code.ToString(), (ex as ServiceException).Details[0]), "Error", MessageBoxButton.OK); return; } } }
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 GetRulePackages() { try { await QueuedTask.Run(async() => { ArcGISPortal portal = ArcGISPortalManager.Current.GetPortal(new Uri(_arcgisOnline)); var query = PortalQueryParameters.CreateForItemsOfType(PortalItemType.RulePackage, "title:\"Paris Rule package 2014\" OR title:\"Venice Rule package 2014\" OR title:\"Extrude/Color/Rooftype Rule package 2014\""); //Execute to return a result set PortalQueryResultSet <PortalItem> results = await ArcGISPortalExtensions.SearchForContentAsync(portal, query); foreach (var item in results.Results.OfType <PortalItem>()) { lock (_rpkLock) { RulePackageCollection.Add(new RulePackage(item)); } } }); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } }
// Initialize the display with a web map and search portal for basemaps private async void mapView_Loaded(object sender, RoutedEventArgs e) { try { progress.Visibility = Visibility.Visible; // Load initial webmap var portal = await ArcGISPortal.CreateAsync(); var item = await ArcGISPortalItem.CreateAsync(portal, "3679c136c2694d0b95bb5e6c3f2b480e"); var webmap = await WebMap.FromPortalItemAsync(item); _currentVM = await WebMapViewModel.LoadAsync(webmap, portal); mapView.Map = _currentVM.Map; // Load portal basemaps var result = await portal.ArcGISPortalInfo.SearchBasemapGalleryAsync(); basemapList.ItemsSource = result.Results; } catch (Exception ex) { MessageBox.Show(ex.Message, "Sample Error"); } finally { progress.Visibility = Visibility.Collapsed; } }
public async Task <bool> SignIn() { IsSigningIn = true; try { bool b = await SignInUsingIdentityManager(); if (b) { Portal = await ArcGISPortal.CreateAsync(App.PortalUri.Uri); //, CancellationToken.None, ((TokenCredential)_credential).Token); if (Portal != null) { CurrentUser = await ArcGISPortalUser.CreateAsync(Portal, ((TokenCredential)_credential).UserName); } SetOrganizationProperties(); IsSigningIn = false; return(true); } } catch (Exception ex) { IsSigningIn = false; var _ = App.ShowExceptionDialog(ex); } IsSigningIn = false; return(false); }
private async void OnSearchMapsClicked(object sender, OnSearchMapEventArgs e) { try { // Get web map portal items from a keyword search IEnumerable <PortalItem> mapItems = null; // Connect to the portal (anonymously) ArcGISPortal portal = await ArcGISPortal.CreateAsync(new Uri(ServerUrl)); // Create a query expression that will get public items of type 'web map' with the keyword(s) in the items tags string queryExpression = $"tags:\"{e.SearchText}\" access:public type: (\"web map\" NOT \"web mapping application\")"; // Create a query parameters object with the expression and a limit of 10 results PortalQueryParameters queryParams = new PortalQueryParameters(queryExpression, 10); // Search the portal using the query parameters and await the results PortalQueryResultSet <PortalItem> findResult = await portal.FindItemsAsync(queryParams); // Get the items from the query results mapItems = findResult.Results; // Show the map results ShowMapList(mapItems); } catch (Exception ex) { new AlertDialog.Builder(this).SetMessage(ex.ToString()).SetTitle("Error").Show(); } }
private async void MyMapView_Loaded(object sender, RoutedEventArgs e) { // ArcGIS Online への参照を取得 var portal = await ArcGISPortal.CreateAsync(new Uri(PORTAL_URL)); // ID を基にアイテムを取得 var item = await ArcGISPortalItem.CreateAsync(portal, "Web マップ ID"); // アイテムを Web マップとして取得 var webmap = await WebMap.FromPortalItemAsync(item); // Web マップを格納するために WebMapViewModel を作成 var vm = await WebMapViewModel.LoadAsync(webmap, portal); // MapView コントロールの Map プロパティに、WebMap を割り当て MyMapView.Map = vm.Map; // グラフィックス オーバーレイが存在しない場合は、新規に追加 if (MyMapView.GraphicsOverlays.Count == 0) { geocodeResultGraphicsOverlay = new GraphicsOverlay() { Renderer = createGeocoordingSymbol(), }; MyMapView.GraphicsOverlays.Add(geocodeResultGraphicsOverlay); } isMapReady = true; }
private async void Initialize() { //住所検索用のジオコーディング タスクを初期化 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; }
// Searches arcgis online for webmaps containing SearchText private async Task SearchArcgisOnline() { try { IsBusy = true; if (_portal == null) { _portal = await ArcGISPortal.CreateAsync(); } var searchParams = new SearchParameters(SearchText + " type: \"web map\" NOT \"web mapping application\" ") { Limit = 20, SortField = "avgrating", SortOrder = QuerySortOrder.Descending, }; var result = await _portal.SearchItemsAsync(searchParams); SearchResults = new ObservableCollection <ArcGISPortalItem>(result.Results); } finally { IsBusy = false; } }
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); featureCollectionLayer.Name = collectionItem.Title; MyMapView.Map.OperationalLayers.Add(featureCollectionLayer); } else { var messageDlg = new MessageDialog("Portal item with ID '" + itemId + "' is not a feature collection.", "Feature Collection"); messageDlg.ShowAsync(); } }catch (Exception ex) { var messageDlg = new MessageDialog("Unable to open item with ID '" + itemId + "': " + ex.Message, "Error"); messageDlg.ShowAsync(); } }
/// <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 void GetMyMaps(object sender, EventArgs e) { // Get web map portal items in the current user's folder or from a keyword search IEnumerable <PortalItem> mapItems = null; ArcGISPortal portal; // Call a sub that will force the user to log in to ArcGIS Online (if they haven't already) var loggedIn = await EnsureLoggedInAsync(); if (!loggedIn) { return; } // Connect to the portal (will connect using the provided credentials) portal = await ArcGISPortal.CreateAsync(new Uri(ArcGISOnlineUrl)); // Get the user's content (items in the root folder and a collection of sub-folders) PortalUserContent myContent = await portal.User.GetContentAsync(); // Get the web map items in the root folder mapItems = from item in myContent.Items where item.Type == PortalItemType.WebMap select item; // Loop through all sub-folders and get web map items, add them to the mapItems collection foreach (PortalFolder folder in myContent.Folders) { IEnumerable <PortalItem> folderItems = await portal.User.GetContentAsync(folder.FolderId); mapItems.Concat(from item in folderItems where item.Type == PortalItemType.WebMap select item); } // Show the list of web maps MapsListView.ItemsSource = mapItems; MapsListView.IsVisible = true; }
// Initialize the display with a web map and search portal for basemaps private async void MyMapView_Loaded(object sender, RoutedEventArgs e) { try { progress.Visibility = Visibility.Visible; // Load initial webmap var portal = await ArcGISPortal.CreateAsync(); var item = await ArcGISPortalItem.CreateAsync(portal, "d2cddd2bb4614cdc915b37349bbab6ce");//"3679c136c2694d0b95bb5e6c3f2b480e"); var webmap = await WebMap.FromPortalItemAsync(item); _currentVM = await WebMapViewModel.LoadAsync(webmap, portal); MyMapView.Map = _currentVM.Map; // Load portal basemaps var result = await portal.ArcGISPortalInfo.SearchBasemapGalleryAsync(); basemapList.ItemsSource = result.Results; basemapList.SelectedItem = result.Results.FirstOrDefault(bm => bm.Title == "Topographic"); } catch (Exception ex) { var _ = new MessageDialog(ex.Message, "Error").ShowAsync(); } finally { progress.Visibility = Visibility.Collapsed; } }
private async void SearchPublicMaps(string searchText) { // Get web map portal items from a keyword search IEnumerable <PortalItem> mapItems = null; ArcGISPortal portal; // Connect to the portal (anonymously) portal = await ArcGISPortal.CreateAsync(new Uri(ArcGISOnlineUrl)); // Create a query expression that will get public items of type 'web map' with the keyword(s) in the items tags var queryExpression = string.Format("tags:\"{0}\" access:public type: (\"web map\" NOT \"web mapping application\")", searchText); // Create a query parameters object with the expression and a limit of 10 results PortalQueryParameters queryParams = new PortalQueryParameters(queryExpression, 10); // Search the portal using the query parameters and await the results PortalQueryResultSet <PortalItem> findResult = await portal.FindItemsAsync(queryParams); // Get the items from the query results mapItems = findResult.Results; // Hide the search controls SearchMapsUI.IsVisible = false; // Show the list of web maps MapsListView.ItemsSource = mapItems; MapsListView.IsVisible = true; }
private async void InitializeArcGISPortal() { _arcGisPortal = await ArcGISPortal.CreateAsync(); // Load portal basemaps var result = await _arcGisPortal.ArcGISPortalInfo.SearchBasemapGalleryAsync(); _basemapGalleryView.ViewModel.Basemaps = new ObservableCollection<ArcGISPortalItem>(result.Results); }
public PortalSpatialSearch() { InitializeComponent(); // Search public web maps on www.arcgis.com arcgisPortal = new ArcGISPortal() { Url = "http://www.arcgis.com/sharing/rest" }; webmapGraphicsLayer = MyMap.Layers["MyGraphicsLayer"] as GraphicsLayer; }
public void InitializePortal(string PortalUrl) { ArcGISPortal arcgisPortal = new ArcGISPortal(); arcgisPortal.InitializeAsync(PortalUrl, (p, ex) => { if (ex == null) { ArcGISPortalInfo portalInfo = p.ArcGISPortalInfo; if (portalInfo == null) { MessageBox.Show("Portal Information could not be retrieved"); return; } PropertiesListBox.Items.Add(string.Format("Current Version: {0}", p.CurrentVersion)); PropertiesListBox.Items.Add(string.Format("Access: {0}", portalInfo.Access)); PropertiesListBox.Items.Add(string.Format("Host Name: {0}", portalInfo.PortalHostname)); PropertiesListBox.Items.Add(string.Format("Name: {0}", portalInfo.PortalName)); PropertiesListBox.Items.Add(string.Format("Mode: {0}", portalInfo.PortalMode)); ESRI.ArcGIS.Client.WebMap.BaseMap basemap = portalInfo.DefaultBaseMap; PropertiesListBox.Items.Add(string.Format("Default BaseMap Title: {0}", basemap.Title)); PropertiesListBox.Items.Add(string.Format("WebMap Layers ({0}):", basemap.Layers.Count)); foreach (WebMapLayer webmapLayer in basemap.Layers) { PropertiesListBox.Items.Add(webmapLayer.Url); } portalInfo.GetFeaturedGroupsAsync((portalgroup, exp) => { if (exp == null) { PropertiesListBox.Items.Add("Groups:"); ListBox listGroups = new ListBox(); listGroups.ItemTemplate = LayoutRoot.Resources["PortalGroupTemplate"] as DataTemplate; listGroups.ItemsSource = portalgroup; PropertiesListBox.Items.Add(listGroups); } }); portalInfo.SearchFeaturedItemsAsync(new SearchParameters() { Limit = 15 }, (result, err) => { if (err == null) { FeaturedMapsList.ItemsSource = result.Results; } }); } else MessageBox.Show("Failed to initialize" + ex.Message.ToString()); }); }
private async void SearchButton_Click(object sender, RoutedEventArgs e) { try { //if first run, get a ref to the portal (ArcGIS Online) if (this.arcGISOnline == null) { //create the uri for the portal var portalUri = new Uri("https://www.arcgis.com/sharing/rest"); //create the portal this.arcGISOnline = await ArcGISPortal.CreateAsync(portalUri); } //create a variable to store search results (collection of portal items IEnumerable<ArcGISPortalItem> results = null; if(this.ItemTypeComboBox.SelectedValue.ToString() == "Basemap") { //basemap search returns web maps that contain the basemap layer var basemapSearch = await this.arcGISOnline.ArcGISPortalInfo.SearchBasemapGalleryAsync(); results = basemapSearch.Results; } else { //get the search term and item type provided it he UI var searchTerm = this.SearchTextBox.Text.Trim(); var searchItem = this.ItemTypeComboBox.SelectedValue.ToString(); // build a query that searches for the specified type // ('web mapping application' is excluded from the search since 'web map' will match those item types too) var queryString = string.Format("\"{0}\" type:(\"{1}\" NOT \"web mapping application\")", searchTerm, searchItem); // create a SearchParameters object, set options var searchParameters = new SearchParameters() { QueryString = queryString, SortField = "avgrating", SortOrder = QuerySortOrder.Descending, Limit = 10 }; //execute the search var itemSearch = await this.arcGISOnline.SearchItemsAsync(searchParameters); results = itemSearch.Results; } //show the results in the list box this.ResultsLIstBox.ItemsSource = results; } catch (Exception ex) { MessageBox.Show(ex.Message, "Error searching portal"); } }
// Loads UI elements and an initial webmap private async void LoadWebMap_Loaded(object sender, RoutedEventArgs e) { _portal = await ArcGISPortal.CreateAsync(); var searchParams = new SearchParameters("type: \"web map\" NOT \"web mapping application\""); var result = await _portal.ArcGISPortalInfo.SearchHomePageFeaturedContentAsync(searchParams); comboWebMap.ItemsSource = result.Results; var webmap = result.Results.FirstOrDefault(); if (webmap != null) { comboWebMap.SelectedIndex = 0; await LoadWebMapAsync(webmap.Id); } }
private async Task LoadMaps(ArcGISPortal portal) { StatusMessage = "Loading maps..."; var task1 = portal.ArcGISPortalInfo.SearchBasemapGalleryAsync(); var task2 = portal.ArcGISPortalInfo.SearchFeaturedItemsAsync(new SearchParameters("") { Limit = 50 }); var items = await task1; Basemaps = items.Results; var groups = new ObservableCollection<MapGroup>(); Groups = groups; groups.Add(new MapGroup() { Name = "Base maps", Items = Basemaps }); IsLoadingBasemaps = false; StatusMessage = string.Format("Connected to {0} ({1})", portal.ArcGISPortalInfo.PortalName, portal.ArcGISPortalInfo.PortalHostname); items = await task2; Featured = items.Results; groups.Add(new MapGroup() { Name = "Featured", Items = Featured }); Groups = groups; }
// Searches arcgis online for webmaps containing SearchText private async Task SearchArcgisOnline() { try { IsBusy = true; if (_portal == null) _portal = await ArcGISPortal.CreateAsync(); var searchParams = new SearchParameters(SearchText + " type: \"web map\" NOT \"web mapping application\" ") { Limit = 20, SortField = "avgrating", SortOrder = QuerySortOrder.Descending, }; var result = await _portal.SearchItemsAsync(searchParams); SearchResults = new ObservableCollection<ArcGISPortalItem>(result.Results); } finally { IsBusy = false; } }
private async Task LoadWebMap(WebMap webMap, ArcGISPortal arcGisPortal) { var vm = await WebMapViewModel.LoadAsync(webMap, arcGisPortal); var mapView = new MapView {Map = vm.Map}; CurrentEsriMapView = mapView; CurrentEsriMapView.MapViewTapped += CurrentEsriMapViewTapped; }
public void TriggerCreateOfflineMapEvent(ArcGisPortalWebMapItem arcGisPortalWebMapItem, ArcGISPortal arcGisPortal) { CreateOfflineMap(arcGisPortalWebMapItem, arcGisPortal); }
public void TriggerLoadWebMapEvent(WebMap webMap, ArcGISPortal arcGisPortal) { LoadWebMap(webMap, arcGisPortal); }
void initializeView() { if (!ArcGISOnlineEnvironment.ArcGISOnline.IsInitialized) // Wait for AGOL environment initialization { EventHandler<EventArgs> onInitialized = null; onInitialized = (o, e) => { ArcGISOnlineEnvironment.ArcGISOnline.Initialized -= onInitialized; initializeView(); }; ArcGISOnlineEnvironment.ArcGISOnline.Initialized += onInitialized; } else { WindowManager manager = View != null && View.WindowManager != null ? View.WindowManager : null; string portalUrl = BaseUri.Scheme == "http" ? ViewerApplication.ArcGISOnlineSharing : ViewerApplication.ArcGISOnlineSecure; // TODO: Investigate difference between ViewerApplication.ArcGISOnlineProxy and ViewerApplication.Proxy ArcGISPortal portal = new ArcGISPortal() { Url = portalUrl, Token = ArcGISOnlineEnvironment.ArcGISOnline.User != null ? ArcGISOnlineEnvironment.ArcGISOnline.User.Token : null, ProxyUrl = ViewerApplication.ArcGISOnlineProxy }; View = new View(ApplicationServices, manager) { IsEditMode = IsEditMode, BaseUrl = BaseUri.ToString(), ApplicationColorSet = ApplicationColorSet, LayoutProvider = new LayoutFileProvider() { LayoutFileContents = layoutFileContents, }, Portal = portal }; if (!string.IsNullOrWhiteSpace(ConfigurationStoreFilePath)) { View.ConfigurationStoreProvider = new ViewerConfigurationStoreProvider(ViewerApplication.GeometryService, ViewerApplication.BingMapsAppId, ViewerApplication.PortalAppId); } View.ProxyUrl = View.DefaultProxyUrl = ViewerApplication.Proxy; layoutResourceDictionaries = new List<ResourceDictionary>(); foreach (string layoutResourceDictionaryFileContent in layoutResourceDictionaryFileContents) { if (!string.IsNullOrWhiteSpace(layoutResourceDictionaryFileContent)) { ResourceDictionary resourceDict = XamlReader.Load(layoutResourceDictionaryFileContent) as ResourceDictionary; if (resourceDict != null) { Application.Current.Resources.MergedDictionaries.Add(resourceDict); layoutResourceDictionaries.Add(resourceDict); } } } View.LayoutResourceDictionaries = layoutResourceDictionaries; if (!string.IsNullOrWhiteSpace(ThemeFilePath)) { View.ThemeProvider = new ThemeProvider() { ThemeFileUrl = ThemeFilePath, }; } if (!string.IsNullOrWhiteSpace(ConnectionsFileFilePath)) { View.ConnectionsProvider = new FileConnectionsProvider() { ConfigurationFile = new DataFile() { IsUrl = true, Path = ConnectionsFileFilePath } }; } if (!string.IsNullOrWhiteSpace(MapConfigurationFilePath)) { FileConfigurationProvider fileConfigurationProvider = ConfigurationProvider ?? new FileConfigurationProvider(); fileConfigurationProvider.ConfigurationFile = new DataFile() { IsUrl = true, Path = MapConfigurationFilePath }; View.ConfigurationProvider = fileConfigurationProvider; } if (!string.IsNullOrWhiteSpace(SymbolConfigurationFilePath)) { View.SymbolConfigProvider = new FileSymbolConfigProvider() { ConfigFileUrl = SymbolConfigurationFilePath, ClassBreaksColorGradientsConfigFileUrl = ClassBreaksColorGradientsConfigFileUrl, HeatMapColorGradientsConfigFileUrl = HeatMapColorGradientsConfigFileUrl, SymbolFolderParentUrl = SymbolFolderParentUrl, UniqueValueColorGradientsConfigFileUrl = UniqueValueColorGradientsConfigFileUrl, }; } View.ExtensionsDataManager = new ExtensionsDataManager() { ExtensionsConfigData = new ExtensionsConfigData(controlsXmlFileContents) }; View.ExtensionBehaviors = getBehaviors(behaviorsXmlFileContents); View.ExtensionLoadFailed += new EventHandler<ExceptionEventArgs>(View_ExtensionLoadFailed); View.ConfigurationLoaded += new EventHandler(View_ConfigurationLoaded); this.Content = View; OnViewInitialized(new ViewEventArgs() { View = View }); } }
/// <summary> /// Search the PKI-secured portal for web maps and display the results in a list box. /// </summary> private async void SearchSecureMapsButton_Click(object sender, RoutedEventArgs e) { // Set the flag variable to indicate we're working with the secure portal // (if the user wants to load a map, we'll need to know which portal it came from) _usingPublicPortal = false; MapItemListBox.Items.Clear(); // Show status message and the status bar MessagesTextBlock.Text = "Searching for web map items on the secure portal."; ProgressStatus.Visibility = Windows.UI.Xaml.Visibility.Visible; var sb = new StringBuilder(); try { // Create an instance of the PKI-secured portal _pkiSecuredPortal = await ArcGISPortal.CreateAsync(new Uri(SecuredPortalUrl)); // Report a successful connection sb.AppendLine("Connected to the portal on " + _pkiSecuredPortal.Uri.Host); sb.AppendLine("Version: " + _pkiSecuredPortal.CurrentVersion); // Report the username used for this connection if (_pkiSecuredPortal.CurrentUser != null) sb.AppendLine("Connected as: " + _pkiSecuredPortal.CurrentUser.UserName); else sb.AppendLine("Anonymous"); // THIS SHOULDN'T HAPPEN! // Search the secured portal for web maps var items = await _pkiSecuredPortal.SearchItemsAsync(new SearchParameters("type:(\"web map\" NOT \"web mapping application\")")); // Build a list of items from the results that shows the map name and stores the item ID (with the Tag property) var resultItems = from r in items.Results select new ListBoxItem { Tag = r.Id, Content = r.Name }; // Add the list items foreach (var itm in resultItems) { MapItemListBox.Items.Add(itm); } } catch (Exception ex) { // Report errors connecting to or searching the secured portal sb.AppendLine(ex.Message); } finally { // Show messages, hide progress bar MessagesTextBlock.Text = sb.ToString(); ProgressStatus.Visibility = Windows.UI.Xaml.Visibility.Collapsed; } }
private async void SignIn_Click(object sender, RoutedEventArgs e) { ResultsListBox.ItemsSource = null; try { var crd = await IdentityManager.Current.GenerateCredentialAsync( DEFAULT_SERVER_URL, UserTextBox.Text, PasswordTextBox.Password); IdentityManager.Current.AddCredential(crd); _portal = await ArcGISPortal.CreateAsync(new Uri(DEFAULT_SERVER_URL)); ResetVisibility(); SignInButton.Content = "Sign Out"; DoSearch(); } catch { MessageBox.Show("Could not log in. Please check credentials."); } }
private async void ShowSignIn_Click(object sender, RoutedEventArgs e) { if (SignInButton.Content.ToString() == "Sign In") { ShadowGrid.Visibility = Visibility.Visible; LoginGrid.Visibility = Visibility.Visible; } else //Sign Out { ResultsListBox.ItemsSource = null; var crd = IdentityManager.Current.FindCredential(DEFAULT_SERVER_URL); IdentityManager.Current.RemoveCredential(crd); _portal = await ArcGISPortal.CreateAsync(new Uri(DEFAULT_SERVER_URL)); ResetVisibility(); SignInButton.Content = "Sign In"; DoSearch(); } }
private async void SearchPortal(ArcGISPortal currentPortal) { MapItemListBox.Items.Clear(); // Show status message and the status bar MessagesTextBlock.Text = "Searching for web map items on the portal at " + currentPortal.Uri.AbsoluteUri; ProgressStatus.Visibility = Visibility.Visible; var messageBuilder = new StringBuilder(); try { // Report connection info messageBuilder.AppendLine("Connected to the portal on " + currentPortal.Uri.Host); messageBuilder.AppendLine("Version: " + currentPortal.CurrentVersion); // Report the user name used for this connection if (currentPortal.CurrentUser != null) { messageBuilder.AppendLine("Connected as: " + currentPortal.CurrentUser.UserName); } else { // (this shouldn't happen for a secure portal) messageBuilder.AppendLine("Anonymous"); } // Search the portal for web maps var items = await currentPortal.SearchItemsAsync(new SearchParameters("type:(\"web map\" NOT \"web mapping application\")")); // Build a list of items from the results that shows the map name and stores the item ID (with the Tag property) var resultItems = from r in items.Results select new ListBoxItem { Tag = r.ItemId, Content = r.Title }; // Add the list items foreach (var itm in resultItems) { MapItemListBox.Items.Add(itm); } } catch (Exception ex) { // Report errors searching the portal messageBuilder.AppendLine(ex.Message); } finally { // Show messages, hide progress bar MessagesTextBlock.Text = messageBuilder.ToString(); ProgressStatus.Visibility = Visibility.Hidden; } }
// Search the IWA-secured portal for web maps and display the results in a list box private async void SearchSecureMapsButtonClick(object sender, RoutedEventArgs e) { // Set the flag variable to indicate this is the secure portal // (if the user wants to load a map, will need to know which portal it came from) _usingPublicPortal = false; try { // Create an instance of the IWA-secured portal _iwaSecuredPortal = await ArcGISPortal.CreateAsync(new Uri(SecuredPortalUrl)); // Call a function to search the portal SearchPortal(_iwaSecuredPortal); } catch (Exception ex) { // Report errors connecting to the secured portal MessagesTextBlock.Text = ex.Message; } }
// Loads the given webmap private async Task LoadWebMapAsync(ArcGISPortalItem portalItem) { try { IsBusy = true; if (_portal == null) _portal = await ArcGISPortal.CreateAsync(); var webmap = await WebMap.FromPortalItemAsync(portalItem); LoadedPortalItem = portalItem; CurrentWebMapVM = await WebMapViewModel.LoadAsync(webmap, _portal); } catch (Exception ex) { var _x = new MessageDialog(ex.Message, "Sample Error").ShowAsync(); } finally { IsBusy = false; } }
private async void SearchArcgisOnline() { try { IsBusy = true; //create Portal instance try { _arcGisPortal = await ArcGISPortal.CreateAsync(_model.DefaultServerUri); } catch (ArcGISWebException agwex) { _model.SetMessageInfo(agwex.Message); if ((int) agwex.Code == 498) { MessageBox.Show("Der Token ist abgelaufen"); } return; } //define search creteria var sb = new StringBuilder(); sb.Append(string.Format("{0} ", SearchText)); sb.Append("type:(\"web map\" NOT \"web mapping application\") "); sb.Append("typekeywords:(\"offline\") "); if (_arcGisPortal.CurrentUser != null && _arcGisPortal.ArcGISPortalInfo != null && !string.IsNullOrEmpty(_arcGisPortal.ArcGISPortalInfo.Id)) { sb.Append(string.Format("orgid:(\"{0}\")", _arcGisPortal.ArcGISPortalInfo.Id)); } var searchParams = new SearchParameters(sb.ToString()) { Limit = 20, SortField = "avgrating", SortOrder = QuerySortOrder.Descending, }; //search for items var result = await _arcGisPortal.SearchItemsAsync(searchParams); //rate the result items foreach (var item in result.Results.Where(x => x.TypeKeywords.Contains("Offline"))) { try { var webMap = await WebMap.FromPortalItemAsync(item); bool isEditable = false; bool isSyncable = false; if (webMap.OperationalLayers.Count > 0) { foreach (var operationalLayer in webMap.OperationalLayers) { if (!operationalLayer.Url.Contains("FeatureServer")) continue; var featureLayer = new FeatureLayer(new Uri(operationalLayer.Url)); await featureLayer.InitializeAsync(); var serviceFeatureTable = featureLayer.FeatureTable as ServiceFeatureTable; var capabilities = serviceFeatureTable.ServiceInfo.Capabilities; foreach (var capability in capabilities) { if (capability == "Editing") { isEditable = true; } if (capability == "Sync") { isSyncable = true; } } if (isEditable) { var arcGisPortalWebMapItem = new ArcGisPortalWebMapItem(item, webMap, isEditable, isSyncable); ArcGisPortalWebMapListBoxItems.Add(new ArcGisPortalWebMapListBoxItem(arcGisPortalWebMapItem, LoadWebMapCommand, CreateOfflineMapCommand)); break; } } } } catch { } } } finally { IsBusy = false; } }
private void apply(object commandParameter) { if (ViewerApplication != null) { if (ViewerApplication.BingMapsAppId != BingMapsAppId) { if (View.Instance != null && View.Instance.ConfigurationStore != null) View.Instance.ConfigurationStore.BingMapsAppId = BingMapsAppId; ViewerApplication.BingMapsAppId = BingMapsAppId; if (View.Instance != null && View.Instance.Map != null) { foreach (Layer layer in View.Instance.Map.Layers) { Client.Bing.TileLayer bingLayer = layer as Client.Bing.TileLayer; if (bingLayer != null && ESRI.ArcGIS.Mapping.Core.LayerExtensions.GetUsesBingAppID(bingLayer)) { bingLayer.Token = ConfigurationStore.Current.BingMapsAppId; bingLayer.Refresh(); } } } } if (ViewerApplication.PortalAppId != PortalAppId) { if (View.Instance != null && View.Instance.ConfigurationStore != null) View.Instance.ConfigurationStore.PortalAppId = PortalAppId; ViewerApplication.PortalAppId = PortalAppId; } if (ViewerApplication.GeometryService != GeometryServiceUrl) { if (View.Instance != null) View.Instance.SetGeometryServiceUrl(GeometryServiceUrl); ViewerApplication.GeometryService = GeometryServiceUrl; } bool portalChanged = false; if (ViewerApplication.ArcGISOnlineSharing != ArcGISOnlineSharing) { if (View.Instance != null) View.Instance.ArcGISOnlineSharing = ArcGISOnlineSharing; ViewerApplication.ArcGISOnlineSharing = ArcGISOnlineSharing; portalChanged = true; } if (ViewerApplication.ArcGISOnlineSecure != ArcGISOnlineSecure) { if (View.Instance != null) View.Instance.ArcGISOnlineSecure = ArcGISOnlineSecure; ViewerApplication.ArcGISOnlineSecure = ArcGISOnlineSecure; portalChanged = true; } if (ViewerApplication.Proxy != Proxy) { if (View.Instance != null) View.Instance.ProxyUrl = Proxy; ViewerApplication.Proxy = Proxy; } if (portalChanged) { ArcGISPortal portal = new ArcGISPortal() { Url = View.Instance.BaseUrl.ToLower().StartsWith("https://") ? ArcGISOnlineSecure : ArcGISOnlineSharing, ProxyUrl = ViewerApplication.ArcGISOnlineProxy }; BuilderApplication.Instance.UpdatingSettings = true; portal.InitializeAsync(portal.Url, (o, ex) => { View.Instance.Portal = portal; BuilderApplication.Instance.UpdatingSettings = false; }); } } raiseChange(); }
/// <summary> /// Initialize application. Load basemaps from ArcGISPortal and selecte first one. /// </summary> protected override async Task InitializeAsync() { Exception exceptionToHandle = null; try { // Store portal instance for later use. Default creates ArcGIS Online portal. _portal = await ArcGISPortal.CreateAsync(); // Get all basemap items that are linked to your portal. Remember that this is dynamic data. var items = await _portal.ArcGISPortalInfo.SearchBasemapGalleryAsync(); Basemaps = new ObservableCollection<ArcGISPortalItem>(items.Results); // Load first basemap on initialization var webmap = await WebMap.FromPortalItemAsync(Basemaps[0]); WebMapViewModel = await WebMapViewModel.LoadAsync(webmap, _portal); IsInitialized = true; } catch (Exception exception) { exceptionToHandle = exception; } if (exceptionToHandle != null) { await MessageService.Instance.ShowMessage(string.Format( "Initialization failed. Error = {0}", exceptionToHandle.ToString()), "An error occured"); } }
private async void LoadMap(ArcGisPortalWebMapItem arcGisPortalWebMapItem, ArcGISPortal arcGisPortal) { _currentArcGisPortalWebMapItem = arcGisPortalWebMapItem; _graphicsOverlay = new GraphicsOverlay(); _graphicsOverlay.Renderer = new SimpleRenderer(); var vm = await WebMapViewModel.LoadAsync(arcGisPortalWebMapItem.WebMap, arcGisPortal); var mapView = new MapView {Map = vm.Map}; mapView.GraphicsOverlays.Add(_graphicsOverlay); CurrentEsriMapView = mapView; IsMapLoaded = true; }