Create and save a map as an ArcGIS PortalItem (i.e. web map).

Use case
Maps can be created programmatically in code and then serialized and saved as an ArcGIS web map. A web map can be shared with others and opened in various applications and APIs throughout the platform, such as ArcGIS Pro, ArcGIS Online, the JavaScript API, Collector, and Explorer.
How to use the sample
- Select the basemap and layers you’d like to add to your map.
- Press the Save button.
- Sign into an ArcGIS Online account.
- Provide a title, tags, and description.
- Save the map.
How it works
- A
Mapis created with aBasemapand a few operational layers. - A
Portalobject is created and loaded. This will issue an authentication challenge, prompting the user to provide credentials. - Once the user is authenticated,
map.SaveAsAsyncis called and a newMapis saved with the specified title, tags, and folder.
Relevant API
- AuthenticationManager
- ChallengeHandler
- GenerateCredentialAsync
- IOAuthAuthorizeHandler
- Map
- Map.SaveAsAsync
- Portal
Tags
ArcGIS Online, OAuth, portal, publish, share, web map
Sample code
// Copyright 2021 Esri.//// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.// You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific// language governing permissions and limitations under the License.
using ArcGIS.Helpers;using Esri.ArcGISRuntime.Geometry;using Esri.ArcGISRuntime.Mapping;using Esri.ArcGISRuntime.Portal;using Esri.ArcGISRuntime.UI;using Microsoft.UI.Xaml;using Microsoft.UI.Xaml.Controls;using System;using System.Collections.Generic;using System.IO;using System.Threading.Tasks;
namespace ArcGIS.WinUI.Samples.AuthorMap{ [ArcGIS.Samples.Shared.Attributes.Sample( name: "Create and save map", category: "Map", description: "Create and save a map as an ArcGIS `PortalItem` (i.e. web map).", instructions: "1. Select the basemap and layers you'd like to add to your map.", tags: new[] { "ArcGIS Online", "OAuth", "portal", "publish", "share", "web map" })] [ArcGIS.Samples.Shared.Attributes.ClassFile("Helpers\\ArcGISLoginPrompt.cs")] public partial class AuthorMap { // String array to store names of the available basemaps private readonly string[] _basemapNames = { "Light Gray", "Topographic", "Streets", "Imagery", "Ocean" };
// Key value pairs of operational layer names and URLs private readonly KeyValuePair<string, string>[] _operationalLayerUrls = { KeyValuePair.Create("World Elevations", "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Elevation/WorldElevations/MapServer"), KeyValuePair.Create("World Cities", "https://sampleserver6.arcgisonline.com/arcgis/rest/services/SampleWorldCities/MapServer/"), KeyValuePair.Create("US Census Data", "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Census/MapServer"), };
public AuthorMap() { InitializeComponent();
// Create the UI, setup the control references and execute initialization _ = Initialize(); }
private async Task Initialize() { ArcGISLoginPrompt.SetChallengeHandler(this);
bool loggedIn = await ArcGISLoginPrompt.EnsureAGOLCredentialAsync();
// Show a plain gray map in the map view if (loggedIn) { MyMapView.Map = new Map(BasemapStyle.ArcGISLightGray); } else MyMapView.Map = new Map();
// Update the UI with basemaps and layers BasemapListBox.ItemsSource = _basemapNames;
// Add a listener for changes in the selected basemap. BasemapListBox.SelectionChanged += BasemapSelectionChanged;
// Update the extent labels whenever the view point (extent) changes MyMapView.ViewpointChanged += (s, evt) => UpdateViewExtentLabels();
OperationalLayerListBox.ItemsSource = _operationalLayerUrls; }
#region UI event handlers
private void LayerSelectionChanged(object sender, SelectionChangedEventArgs e) { // Call a function to add operational layers to the map AddOperationalLayers(); }
private async void SaveMapClicked(object sender, RoutedEventArgs e) { try { // Show the progress bar so the user knows work is happening SaveProgressBar.Visibility = Visibility.Visible;
// Get the current map Map myMap = MyMapView.Map;
// Apply the current extent as the map's initial extent myMap.InitialViewpoint = MyMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry);
// Export the current map view to use as the item's thumbnail RuntimeImage thumbnailImg = await MyMapView.ExportImageAsync();
// See if the map has already been saved (has an associated portal item) if (myMap.Item == null) { // Get information for the new portal item string title = TitleTextBox.Text; string description = DescriptionTextBox.Text; string tagText = TagsTextBox.Text;
// Make sure all required info was entered if (string.IsNullOrEmpty(title) || string.IsNullOrEmpty(description) || string.IsNullOrEmpty(tagText)) { throw new Exception("Please enter a title, description, and some tags to describe the map."); }
// Call a function to save the map as a new portal item await SaveNewMapAsync(MyMapView.Map, title, description, tagText.Split(','), thumbnailImg);
// Report a successful save await new MessageDialog2("Saved '" + title + "' to ArcGIS Online!", "Map Saved").ShowAsync(); } else { // This is not the initial save, call SaveAsync to save changes to the existing portal item await myMap.SaveAsync();
// Get the file stream from the new thumbnail image Stream imageStream = await thumbnailImg.GetEncodedBufferAsync();
// Update the item thumbnail ((PortalItem)myMap.Item).SetThumbnail(imageStream); await myMap.SaveAsync();
// Report update was successful await new MessageDialog2("Saved changes to '" + myMap.Item.Title + "'", "Updates Saved").ShowAsync(); } } catch (Exception ex) { // Report error message await new MessageDialog2("Error saving map to ArcGIS Online: " + ex.Message).ShowAsync(); } finally { // Hide the progress bar SaveProgressBar.Visibility = Visibility.Collapsed; } }
private void NewMapClicked(object sender, RoutedEventArgs e) { // Create a new map (will not have an associated PortalItem) MyMapView.Map = new Map(BasemapStyle.ArcGISLightGray); MyMapView.Map.Basemap.LoadAsync();
// Reset the basemap selection in the UI BasemapListBox.SelectedIndex = 0;
// Reset the layer selection in the UI; OperationalLayerListBox.SelectedIndex = -1;
// Reset the extent labels UpdateViewExtentLabels(); }
#endregion UI event handlers
private void ApplyBasemap(string basemapName) { // Set the basemap for the map according to the user's choice in the list box. switch (basemapName) { case "Light Gray": MyMapView.Map.Basemap = new Basemap(BasemapStyle.ArcGISLightGray); break;
case "Topographic": MyMapView.Map.Basemap = new Basemap(BasemapStyle.ArcGISTopographic); break;
case "Streets": MyMapView.Map.Basemap = new Basemap(BasemapStyle.ArcGISStreets); break;
case "Imagery": MyMapView.Map.Basemap = new Basemap(BasemapStyle.ArcGISImagery); break;
case "Ocean": MyMapView.Map.Basemap = new Basemap(BasemapStyle.ArcGISOceans); break; }
MyMapView.Map.Basemap.LoadAsync(); }
private void AddOperationalLayers() { // Clear the operational layers from the map Map myMap = MyMapView.Map; myMap.OperationalLayers.Clear();
// Loop through the selected items in the operational layers list box foreach (KeyValuePair<string, string> item in OperationalLayerListBox.SelectedItems) { // Get the service uri for each selected item KeyValuePair<string, string> layerInfo = item; Uri layerUri = new Uri(layerInfo.Value);
// Create a new map image layer, set it 50% opaque, and add it to the map ArcGISMapImageLayer layer = new ArcGISMapImageLayer(layerUri) { Opacity = 0.5 }; myMap.OperationalLayers.Add(layer); } }
private async Task SaveNewMapAsync(Map myMap, string title, string description, string[] tags, RuntimeImage img) { await ArcGISLoginPrompt.EnsureAGOLCredentialAsync();
// 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); }
private void UpdateViewExtentLabels() { // Get the current view point for the map view Viewpoint currentViewpoint = MyMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry); if (currentViewpoint == null) { return; }
// Get the current map extent (envelope) from the view point Envelope currentExtent = currentViewpoint.TargetGeometry as Envelope;
// Project the current extent to geographic coordinates (longitude / latitude) Envelope currentGeoExtent = (Envelope)currentExtent.Project(SpatialReferences.Wgs84);
// Fill the app text boxes with min / max longitude (x) and latitude (y) to four decimal places XMinTextBox.Text = currentGeoExtent.XMin.ToString("0.####"); YMinTextBox.Text = currentGeoExtent.YMin.ToString("0.####"); XMaxTextBox.Text = currentGeoExtent.XMax.ToString("0.####"); YMaxTextBox.Text = currentGeoExtent.YMax.ToString("0.####"); }
private void BasemapSelectionChanged(object sender, SelectionChangedEventArgs e) { // Get the name of the desired basemap string name = e.AddedItems[0].ToString();
// Apply the basemap to the current map ApplyBasemap(name); } }}<UserControl x:Class="ArcGIS.WinUI.Samples.AuthorMap.AuthorMap" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:esriUI="using:Esri.ArcGISRuntime.UI.Controls"> <UserControl.Resources> <Style TargetType="TextBlock"> <Setter Property="FontWeight" Value="SemiBold" /> <Setter Property="HorizontalAlignment" Value="Center" /> <Setter Property="VerticalAlignment" Value="Center" /> <Setter Property="Margin" Value="0,2.5,0,2.5" /> </Style> <Style TargetType="TextBox"> <Setter Property="Margin" Value="0,2.5,0,2.5" /> <Setter Property="Padding" Value="2.5" /> <Setter Property="HorizontalAlignment" Value="Stretch" /> </Style> <Style TargetType="Button"> <Setter Property="HorizontalAlignment" Value="Stretch" /> <Setter Property="Margin" Value="0,2.5,0,2.5" /> </Style> </UserControl.Resources> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition Width="300" /> </Grid.ColumnDefinitions> <ScrollViewer Grid.Column="1" Padding="5"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <TextBlock Text="Select a basemap" /> <ComboBox x:Name="BasemapListBox" Grid.Row="1" HorizontalAlignment="Stretch" /> <TextBlock Grid.Row="2" Text="Choose layers" /> <ListBox x:Name="OperationalLayerListBox" Grid.Row="3" SelectionChanged="LayerSelectionChanged" SelectionMode="Multiple"> <ListBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding Key}" /> </DataTemplate> </ListBox.ItemTemplate> </ListBox> <TextBlock Grid.Row="4" Grid.Column="0" Text="Pan and zoom to set initial extent" /> <Grid Grid.Row="5"> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <TextBlock Grid.Row="0" Grid.Column="0" Margin="0,0,5,0" Text="X Min:" /> <TextBox x:Name="XMinTextBox" Grid.Row="0" Grid.Column="1" IsReadOnly="True" /> <TextBlock Grid.Row="1" Grid.Column="0" Margin="0,0,5,0" Text="Y Min:" /> <TextBox x:Name="YMinTextBox" Grid.Row="1" Grid.Column="1" IsReadOnly="True" /> <TextBlock Grid.Row="2" Grid.Column="0" Margin="0,0,5,0" Text="X Max:" /> <TextBox x:Name="XMaxTextBox" Grid.Row="2" Grid.Column="1" IsReadOnly="True" /> <TextBlock Grid.Row="3" Grid.Column="0" Margin="0,0,5,0" Text="Y Max:" /> <TextBox x:Name="YMaxTextBox" Grid.Row="3" Grid.Column="1" IsReadOnly="True" /> </Grid> <Button Grid.Row="6" Click="NewMapClicked" Content="New map" /> <Grid x:Name="SaveMapGrid" Grid.Row="7" Margin="10"> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <TextBlock Margin="0,0,5,0" HorizontalAlignment="Right" Text="Title:" /> <TextBox x:Name="TitleTextBox" Grid.Row="0" Grid.Column="1" Text="My Map" /> <TextBlock Grid.Row="1" Grid.Column="0" Margin="0,0,5,0" HorizontalAlignment="Right" Text="Description:" /> <TextBox x:Name="DescriptionTextBox" Grid.Row="1" Grid.Column="1" Text="Authored and saved using ArcGIS Maps SDK for .NET." TextWrapping="Wrap" /> <TextBlock Grid.Row="2" Grid.Column="0" Margin="0,0,5,0" HorizontalAlignment="Right" Text="Tags:" /> <TextBox x:Name="TagsTextBox" Grid.Row="2" Grid.Column="1" Text="ArcGIS, Sample" /> <Button Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="2" Click="SaveMapClicked" Content="Save map to portal" IsEnabled="{Binding ElementName=MyMapView}" /> <ProgressBar x:Name="SaveProgressBar" Grid.Row="4" Grid.Column="0" Grid.ColumnSpan="2" Height="15" Margin="10,0,10,0" HorizontalAlignment="Stretch" IsIndeterminate="True" Visibility="Collapsed" /> </Grid> </Grid> </ScrollViewer> <esriUI:MapView x:Name="MyMapView" Grid.Column="0" /> </Grid></UserControl>// Copyright 2021 Esri.//// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.// You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific// language governing permissions and limitations under the License.
using ArcGIS.WinUI;using Esri.ArcGISRuntime.Security;using Microsoft.UI.Dispatching;using Microsoft.UI.Xaml.Controls;using Microsoft.Web.WebView2.Core;using System;using System.Collections.Generic;using System.Diagnostics;using System.Threading.Tasks;
namespace ArcGIS.Helpers{ internal static class ArcGISLoginPrompt { private const string ArcGISOnlineUrl = "https://www.arcgis.com/sharing/rest";
// - The Client ID for an app registered with the server (the ID below is for a public app created by the ArcGIS Maps SDK for Native Apps team). private const string AppClientId = "lgAdHkYZYlwwfAhC";
// - An optional client secret for the app (only needed for the OAuthClientCredentials authorization type). private const string ClientSecret = "";
// - A URL for redirecting after a successful authorization (this must be a URL configured with the app). private const string OAuthRedirectUrl = "my-ags-app://auth";
public static async Task<bool> EnsureAGOLCredentialAsync() { Credential currentCredential = AuthenticationManager.Current.FindCredential(new Uri(ArcGISOnlineUrl), AuthenticationType.Token); if (currentCredential != null) { return true; // already logged in }
try { var userConfig = new OAuthUserConfiguration(new Uri(ArcGISOnlineUrl), AppClientId, new Uri(OAuthRedirectUrl)); Credential cred = await OAuthUserCredential.CreateAsync(userConfig); AuthenticationManager.Current.AddCredential(cred); } catch (OperationCanceledException) { // OAuth login was canceled, no need to display error to user. } catch (Exception ex) { // Login failure await new MessageDialog2(ex.Message, "Login failed").ShowAsync(); } return false; }
public static void SetChallengeHandler(UserControl sample) { var userConfig = new OAuthUserConfiguration(new Uri(ArcGISOnlineUrl), AppClientId, new Uri(OAuthRedirectUrl)); AuthenticationManager.Current.OAuthUserConfigurations.Add(userConfig); AuthenticationManager.Current.OAuthHandler = new OAuthAuthorize(sample); } }
#region OAuth handler
public class OAuthAuthorize : IOAuthHandler { // Window to contain the OAuth UI. private ContentDialog _authWindow;
// Use a TaskCompletionSource to track the completion of the authorization. private TaskCompletionSource<IDictionary<string, string>> _tcs;
// URL for the authorization callback result (the redirect URI configured for your application). private Uri _redirectUrl;
// URL that handles the OAuth request. private Uri _authorizeUrl; private UserControl sample;
public OAuthAuthorize(UserControl sample) { this.sample = sample; }
// Function to handle authorization requests, takes the URIs for the secured service, the authorization endpoint, and the redirect URI. public Task<IDictionary<string, string>> LoginAsync(OAuthLoginParameters parameters) { if (_tcs != null && !_tcs.Task.IsCompleted) throw new Exception("Task in progress");
_tcs = new TaskCompletionSource<IDictionary<string, string>>();
// Store the authorization and redirect URLs. _authorizeUrl = parameters.AuthorizeUri; _redirectUrl = parameters.RedirectUri;
// Call a function to show the login controls, make sure it runs on the UI thread for this app. sample.DispatcherQueue.TryEnqueue(DispatcherQueuePriority.Normal, () => { _ = AuthorizeOnUIThread(parameters.AuthorizeUri); });
// Return the task associated with the TaskCompletionSource. return _tcs.Task; }
// Challenge for OAuth credentials on the UI thread. private async Task AuthorizeOnUIThread(Uri authorizeUri) { // Create a WebBrowser control to display the authorize page. WebView2 webBrowser = new WebView2 { Width = 500, Height = 500, RequestedTheme = Microsoft.UI.Xaml.ElementTheme.Light };
// Handle the navigation event for the browser to check for a response to the redirect URL. webBrowser.NavigationStarting += NavigationStarted;
// Display the web browser in a new window. _authWindow = new ContentDialog { Content = webBrowser, XamlRoot = sample.XamlRoot, CloseButtonText = "Close", };
// Handle the window closed event then navigate to the authorize url. _authWindow.Closed += OnWindowClosed2;
try { // Load the web view and navigate to the Uri. await webBrowser.EnsureCoreWebView2Async(); webBrowser.Source = authorizeUri;
// Display the window. await _authWindow.ShowAsync(); } catch (Exception ex) { Debug.WriteLine(ex.Message); _tcs.SetCanceled(); } }
// Handle browser navigation (content changing). private void NavigationStarted(WebView2 sender, CoreWebView2NavigationStartingEventArgs args) { // Check for a response to the callback url. const string portalApprovalMarker = "/oauth2/approval";
Uri uri = new Uri(args.Uri);
// If no browser, uri, or an empty url, return. if (sender == null || uri == null || string.IsNullOrEmpty(uri.AbsoluteUri)) return;
// Check for redirect. bool isRedirected = _redirectUrl.IsBaseOf(uri) || _redirectUrl.AbsoluteUri.Contains(portalApprovalMarker) && uri.AbsoluteUri.Contains(portalApprovalMarker);
// Check if browser was redirected to the callback URL. (This indicates succesful authentication.) if (isRedirected) { args.Cancel = true;
// Call a helper function to decode the response parameters. IDictionary<string, string> authResponse = DecodeParameters(uri);
// Set the result for the task completion source. _tcs.SetResult(authResponse);
// Close the window. if (_authWindow != null) { _authWindow.Hide(); } } }
// Handle the browser window closing. private void OnWindowClosed2(ContentDialog sender, ContentDialogClosedEventArgs args) { // If the task wasn't completed, the user must have closed the window without logging in. if (!_tcs.Task.IsCompleted) { // Set the task completion source exception to indicate a canceled operation. _tcs.SetCanceled(); }
_authWindow = null; }
private static IDictionary<string, string> DecodeParameters(Uri uri) { // Create a dictionary of key value pairs returned in an OAuth authorization response URI query string. string answer = "";
// Get the values from the URI fragment or query string. if (!string.IsNullOrEmpty(uri.Fragment)) { answer = uri.Fragment.Substring(1); } else { if (!string.IsNullOrEmpty(uri.Query)) { answer = uri.Query.Substring(1); } }
// Parse parameters into key / value pairs. Dictionary<string, string> keyValueDictionary = new Dictionary<string, string>(); string[] keysAndValues = answer.Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries); foreach (string kvString in keysAndValues) { string[] pair = kvString.Split('='); string key = pair[0]; string value = string.Empty; if (key.Length > 1) { value = Uri.UnescapeDataString(pair[1]); }
keyValueDictionary.Add(key, value); }
// Return the dictionary of string keys/values. return keyValueDictionary; } }
#endregion OAuth handler}