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
namespace ArcGIS.Samples.AuthorMap{ public partial class SaveMapPage : ContentPage { // Raise an event so the listener can access input values when the form has been completed public event EventHandler<SaveMapEventArgs> OnSaveClicked;
public SaveMapPage() { InitializeComponent(); }
// If updating an existing map item, show the existing item info and disable changing info public void ShowForUpdate(string title, string description, string[] tags) { // Item title MapTitleEntry.Text = title; MapTitleEntry.IsEnabled = false;
// Item description MapDescriptionEntry.Text = description; MapDescriptionEntry.IsEnabled = false;
// Item tags MapTagsEntry.Text = string.Join(",", tags); MapTagsEntry.IsEnabled = false;
// Show 'Update' rather than 'Save' for button text SaveMapButton.Text = "Update"; }
// A click handler for the save map button private void SaveButtonClicked(object sender, EventArgs e) { try { // Get information for the new portal item string title = MapTitleEntry.Text; string description = MapDescriptionEntry.Text; string[] tags = MapTagsEntry.Text.Split(',');
// Make sure all required info was entered if (string.IsNullOrEmpty(title) || string.IsNullOrEmpty(description) || tags.Length == 0) { throw new Exception("Please enter a title, description, and some tags to describe the map."); }
// Create a new OnSaveMapEventArgs object to store the information entered by the user SaveMapEventArgs mapSavedArgs = new SaveMapEventArgs(title, description, tags);
// Raise the OnSaveClicked event so the main activity can handle the event and save the map OnSaveClicked?.Invoke(this, mapSavedArgs);
// Close the dialog Navigation.PopAsync(); } catch (Exception ex) { // Show the exception message (dialog will stay open so user can try again) DisplayAlert("Error", ex.Message, "OK"); } }
private void CancelButtonClicked(object sender, EventArgs e) { // If the user cancels, just navigate back to the previous page Navigation.PopAsync(); } }
// Custom EventArgs class for containing portal item properties when saving a map public class SaveMapEventArgs : EventArgs { // Portal item title public string MapTitle { get; set; }
// Portal item description public string MapDescription { get; set; }
// Portal item tags public string[] Tags { get; set; }
public SaveMapEventArgs(string title, string description, string[] tags) : base() { MapTitle = title; MapDescription = description; Tags = tags; } }}<?xml version="1.0" encoding="utf-8" ?><ContentPage x:Class="ArcGIS.Samples.AuthorMap.SaveMapPage" xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"> <Grid x:Name="SaveMapUI" ColumnDefinitions="auto,auto" ColumnSpacing="10" HorizontalOptions="Center" RowDefinitions="auto,auto,auto,auto" RowSpacing="10" VerticalOptions="Center"> <Label Grid.Row="0" Grid.Column="0" Text="Title:" VerticalTextAlignment="Center" /> <Entry x:Name="MapTitleEntry" Grid.Row="0" Grid.Column="1" Placeholder="Required" /> <Label Grid.Row="1" Grid.Column="0" Text="Description:" VerticalTextAlignment="Center" /> <Entry x:Name="MapDescriptionEntry" Grid.Row="1" Grid.Column="1" Placeholder="Required" /> <Label Grid.Row="2" Grid.Column="0" Text="Tags:" VerticalTextAlignment="Center" /> <Entry x:Name="MapTagsEntry" Grid.Row="2" Grid.Column="1" Text="ArcGIS, Webmap" /> <Button Grid.Row="3" Grid.Column="0" Clicked="CancelButtonClicked" Text="Cancel" /> <Button x:Name="SaveMapButton" Grid.Row="3" Grid.Column="1" Clicked="SaveButtonClicked" Text="Save" /> </Grid></ContentPage>// Copyright 2022 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.Mapping;using Esri.ArcGISRuntime.Portal;using Esri.ArcGISRuntime.UI;
namespace ArcGIS.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("SaveMapPage.xaml.cs", "SaveMapPage.xaml", "Helpers/ArcGISLoginPrompt.cs")] [ArcGIS.Samples.Shared.Attributes.XamlFiles()] public partial class AuthorMap : ContentPage { private const string ArcGISOnlineUrl = "https://www.arcgis.com/sharing/rest";
// String array to store names of the available basemaps. private Dictionary<string, BasemapStyle> _basemaps = new Dictionary<string, BasemapStyle> { {"Light Gray", BasemapStyle.ArcGISLightGray }, {"Topographic", BasemapStyle.ArcGISTopographic }, {"Streets", BasemapStyle.ArcGISStreets }, {"Imagery", BasemapStyle.ArcGISImageryStandard }, {"Ocean", BasemapStyle.ArcGISOceans }, };
// Dictionary of operational layer names and URLs. private Dictionary<string, string> _operationalLayerUrls = new Dictionary<string, string> { {"World Elevations", "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Elevation/WorldElevations/MapServer"}, {"World Cities", "https://sampleserver6.arcgisonline.com/arcgis/rest/services/SampleWorldCities/MapServer/" }, {"US Census Data", "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Census/MapServer"} };
public AuthorMap() { InitializeComponent(); _ = Initialize(); }
private async Task Initialize() { ArcGISLoginPrompt.SetChallengeHandler(); 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(); }
private void ShowSaveMapUI(object sender, EventArgs e) { // Create a SaveMapPage page for getting user input for the new web map item. SaveMapPage mapInputForm = new SaveMapPage();
// If an existing map, show the UI for updating the item. Item mapItem = MyMapView.Map.Item; if (mapItem != null) { mapInputForm.ShowForUpdate(mapItem.Title, mapItem.Description, mapItem.Tags.ToArray()); }
// Handle the save button click event on the page. mapInputForm.OnSaveClicked += SaveMapAsync;
// Navigate to the SaveMapPage UI. Shell.Current.Navigation.PushAsync(mapInputForm); }
// Event handler to get information entered by the user and save the map. private async void SaveMapAsync(object sender, SaveMapEventArgs e) { // Get the current map Map myMap = MyMapView.Map;
try { // Make sure the user is logged in to ArcGIS Online. bool loggedIn = await ArcGISLoginPrompt.EnsureAGOLCredentialAsync(); if (!loggedIn) return;
// Load the current map before saving to portal. await myMap.LoadAsync();
// Show the progress bar so the user knows work is happening. SaveMapProgressBar.IsVisible = true;
// Get information entered by the user for the new portal item properties. string title = e.MapTitle; string description = e.MapDescription; string[] tags = e.Tags;
// Apply the current extent as the map's initial extent. myMap.InitialViewpoint = MyMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry);
// Export the current map view for the item's thumbnail. RuntimeImage thumbnailImage = await MyMapView.ExportImageAsync();
// See if the map has already been saved (has an associated portal item). if (myMap.Item == null) { // Get the ArcGIS Online portal (will use credential from login above). ArcGISPortal agsOnline = await ArcGISPortal.CreateAsync(new Uri(ArcGISOnlineUrl));
// 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, thumbnailImage);
// Report a successful save. await Application.Current.Windows[0].Page.DisplayAlert("Map Saved", "Saved '" + title + "' to ArcGIS Online!", "OK"); } 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 thumbnailImage.GetEncodedBufferAsync();
// Update the item thumbnail. ((PortalItem)myMap.Item).SetThumbnail(imageStream); await myMap.SaveAsync();
// Report update was successful. await Application.Current.Windows[0].Page.DisplayAlert("Updates Saved", "Saved changes to '" + myMap.Item.Title + "'", "OK"); } } catch (Exception ex) { // Show the exception message. await Application.Current.Windows[0].Page.DisplayAlert("Unable to save map", ex.Message, "OK"); } finally { // Hide the progress bar. SaveMapProgressBar.IsVisible = false; } }
private void NewMapButtonClick(object sender, EventArgs e) { // Create a new map (will not have an associated PortalItem). MyMapView.Map = new Map(BasemapStyle.ArcGISLightGray); MyMapView.Map.Basemap.LoadAsync(); }
private async void Basemap_Clicked(object sender, EventArgs e) { try { string selectionName = await Application.Current.Windows[0].Page.DisplayActionSheet("Select basemap", "Cancel", null, _basemaps.Keys.ToArray());
if (selectionName == "Cancel") return;
MyMapView.Map.Basemap = new Basemap(_basemaps[selectionName]); await MyMapView.Map.Basemap.LoadAsync(); } // Do nothing with cancellation exception from action sheet. catch { } }
private async void Add_Clicked(object sender, EventArgs e) { try { string[] inMapNames = MyMapView.Map.OperationalLayers.Select(l => l.Name).ToArray(); string[] optionNames = _operationalLayerUrls.Where(l => !inMapNames.Contains(l.Key)).Select(l => l.Key).ToArray(); string selectionName = await Application.Current.Windows[0].Page.DisplayActionSheet("Select layer to add", "Cancel", null, optionNames);
if (selectionName == "Cancel") return;
// Add the layer. Uri layerUri = new Uri(_operationalLayerUrls[selectionName]);
// Create and add a new map image layer var layer = new ArcGISMapImageLayer(layerUri); layer.Name = selectionName; layer.Opacity = 0.5; MyMapView.Map.OperationalLayers.Add(layer); } // Do nothing with cancellation exception from action sheet. catch { } }
private async void Remove_Clicked(object sender, EventArgs e) { try { string selectionName = await Application.Current.Windows[0].Page.DisplayActionSheet("Select layer to remove", "Cancel", null, MyMapView.Map.OperationalLayers.Select(l => l.Name).ToArray());
if (selectionName == "Cancel") return;
Layer layer = MyMapView.Map.OperationalLayers.Single(l => l.Name == selectionName); MyMapView.Map.OperationalLayers.Remove(layer); } // Do nothing with cancellation exception from action sheet. catch { } } }}<?xml version="1.0" encoding="utf-8" ?><ContentPage x:Class="ArcGIS.Samples.AuthorMap.AuthorMap" xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:esriUI="clr-namespace:Esri.ArcGISRuntime.Maui;assembly=Esri.ArcGISRuntime.Maui"> <Grid Style="{DynamicResource EsriSampleContainer}"> <esriUI:MapView x:Name="MyMapView" Style="{DynamicResource EsriSampleGeoView}" /> <ActivityIndicator x:Name="SaveMapProgressBar" Grid.RowSpan="2" Grid.ColumnSpan="2" HeightRequest="40" IsRunning="True" IsVisible="False" /> <Border MinimumWidthRequest="360" Style="{DynamicResource EsriSampleControlPanel}"> <ScrollView Orientation="Horizontal"> <HorizontalStackLayout Padding="5" Spacing="5"> <Button Clicked="Basemap_Clicked" Text="Basemap" /> <Button Clicked="Add_Clicked" Text="Add" /> <Button Clicked="Remove_Clicked" Text="Remove" /> <Button Clicked="NewMapButtonClick" Text="New" /> <Button Clicked="ShowSaveMapUI" Text="Save" /> </HorizontalStackLayout> </ScrollView> </Border> </Grid></ContentPage>// Copyright 2022 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 Esri.ArcGISRuntime.Security;
#if ANDROID
using Android.App;using Application = Microsoft.Maui.Controls.Application;using Android.Content;using Android.Content.PM;
#endif
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). public const string AppClientId = @"NDiGU6O6UiscRDPw";
// - 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 = @"maui-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) { await Application.Current.Windows[0].Page.DisplayAlert("Login failed", ex.Message, "OK"); } return false; }
public static void SetChallengeHandler() { var userConfig = new OAuthUserConfiguration(new Uri(ArcGISOnlineUrl), AppClientId, new Uri(OAuthRedirectUrl)); AuthenticationManager.Current.OAuthUserConfigurations.Add(userConfig); AuthenticationManager.Current.OAuthHandler = new OAuthAuthorize(); } }
#region IOAuthAuthorizationHandler implementation
public class OAuthAuthorize : IOAuthHandler {#if IOS || MACCATALYST TaskCompletionSource<IDictionary<string, string>> _taskCompletionSource;
public Task<IDictionary<string, string>> LoginAsync(OAuthLoginParameters parameters) { _taskCompletionSource = new TaskCompletionSource<IDictionary<string, string>>(); Microsoft.Maui.ApplicationModel.MainThread.BeginInvokeOnMainThread(async () => { try { var result = await WebAuthenticator.AuthenticateAsync(parameters.AuthorizeUri, parameters.RedirectUri); _taskCompletionSource.TrySetResult(result.Properties); } catch (Exception ex) { _taskCompletionSource.TrySetException(ex); } }); return _taskCompletionSource.Task; }#elif ANDROID public async Task<IDictionary<string, string>> LoginAsync(OAuthLoginParameters parameters) { var result = await WebAuthenticator.AuthenticateAsync(parameters.AuthorizeUri, parameters.RedirectUri); return result.Properties; }#elif WINDOWS public async Task<IDictionary<string, string>> LoginAsync(OAuthLoginParameters parameters) { var result = await WinUIEx.WebAuthenticator.AuthenticateAsync(parameters.AuthorizeUri, parameters.RedirectUri); return result.Properties; }#else public Task<IDictionary<string, string>> LoginAsync(OAuthLoginParameters parameters) { throw new NotImplementedException(); }#endif}
#if ANDROID
[Activity(NoHistory = true, Exported = true, LaunchMode = LaunchMode.SingleTop)] [IntentFilter(new[] { Intent.ActionView }, Categories = new[] { Intent.CategoryDefault, Intent.CategoryBrowsable }, DataScheme = "maui-ags-app", DataHost = "auth")] public class WebAuthenticationCallbackActivity : WebAuthenticatorCallbackActivity { }
#endif
#endregion IOAuthAuthorizationHandler implementation}