// 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;
            }
        }
Esempio n. 2
0
        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 GetMyMaps()
        {
            // Get web map portal items in the current user's folder
            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(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
            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 map results
            ShowMapList(mapItems);
        }
Esempio n. 4
0
        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 (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(new Uri(ServerUrl));

            // 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>
        /// 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;
            }
        }
Esempio n. 6
0
        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");
            }
        }
        // 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);
            }
        }
        /// <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 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;
        }
Esempio n. 10
0
        /// <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);
            }
        }
        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
            {
                // 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)
            {
                MessageBox.Show("Error displaying map: " + ex.Message);
            }
        }
        public async Task <bool> GetAnonymousAccessStatusAsync()
        {
            bool b = false;

            if (PortalService.CurrentPortalService.Portal != null)
            {
                b = PortalService.CurrentPortalService.Portal.ArcGISPortalInfo.Access == PortalAccess.Public;
            }
            else
            {
                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);

                ArcGISPortal p = null;
                try
                {
                    p = await ArcGISPortal.CreateAsync(App.PortalUri.Uri);
                }
                catch
                {
                }

                if (p != null && p.ArcGISPortalInfo != null)
                {
                    b = p.ArcGISPortalInfo.Access == PortalAccess.Public;
                }

                // Restore ChallengeHandler
                IdentityManager.Current.ChallengeHandler = challengeHandler;
            }

            return(b);
        }
        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 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");
            }
        }
        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 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;
        }
Esempio n. 17
0
        // 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;
            }
        }
Esempio n. 18
0
        // 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 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();
            }
        }
Esempio n. 20
0
        // 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;
            }
        }
Esempio n. 21
0
        private async void GetMyMaps(object sender, EventArgs e)
        {
            // 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)
            ArcGISPortal 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
            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 list of web maps
            MapsListView.ItemsSource = mapItems;
            MapsListView.IsVisible   = true;
        }
        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;
        }
Esempio n. 23
0
        // 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();
        }
Esempio n. 24
0
        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)
                    {
                        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");
            }
        }
Esempio n. 25
0
        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;
            }
        }
        // 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;
            }
        }
Esempio n. 27
0
        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;
        }
Esempio n. 28
0
        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);
        }
Esempio n. 29
0
        // Loads the given webmap
        private async Task <Map> LoadWebMapAsync(WebMap webmap)
        {
            var portal = await ArcGISPortal.CreateAsync();

            var vm = await WebMapViewModel.LoadAsync(webmap, portal);

            return(vm.Map);
        }
Esempio n. 30
0
        private async Task InitializeOnlineMap()
        {
            var portal = await ArcGISPortal.CreateAsync();

            var item = await PortalItem.CreateAsync(portal, "a5283e945e69456e9a4d1d29a0e0796e");

            TheMap.Map = new Map(item);
        }