Skip To Content ArcGIS for Developers Sign In Dashboard

ArcGIS Runtime SDK for .NET

Manage operational layers

This code sample is available for these platforms:
View Sample on GitHub

Add, remove, and reorder operational layers in a map.

Manage Operational Layers App

How to use the sample

Use the buttons on the layer list entries to re-arrange the layers. Tapping the up or down arrows will move the layers up or down within the lists. Tapping the right arrow will move the layer to the other list.

How it works

A map's OperationalLayers collection controls which layers are visualized. MapView automatically updates the visualization when the Map changes. A separate collection holds layers that have been removed from the operational layers.

Relevant API

  • Map
  • ArcGISMapImageLayer
  • MapView
  • MapView.OperationalLayers

Tags

Map, scene, operational, hide, remove, add

Sample Code

<?xml version="1.0" encoding="utf-8"?>

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:esriUI="clr-namespace:Esri.ArcGISRuntime.Xamarin.Forms;assembly=Esri.ArcGISRuntime.Xamarin.Forms"
             xmlns:mapping="clr-namespace:Esri.ArcGISRuntime.Mapping;assembly=Esri.ArcGISRuntime"
             xmlns:resources="clr-namespace:Forms.Resources;assembly=ArcGISRuntime"
             x:Class="ArcGISRuntimeXamarin.Samples.ManageOperationalLayers.ManageOperationalLayers">
    <ContentPage.Resources>
        <DataTemplate x:Key="LayerListTemplate" x:DataType="mapping:Layer">
            <ViewCell>
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*" />
                        <ColumnDefinition Width="Auto" />
                        <ColumnDefinition Width="Auto" />
                        <ColumnDefinition Width="Auto" />
                    </Grid.ColumnDefinitions>
                    <Label Text="{Binding Name}" Grid.Column="0"
                           VerticalTextAlignment="Center" Margin="5" />
                    <Button Text="⬆" Grid.Column="1" Clicked="PromoteButton_Clicked" />
                    <Button Text="⬇" Grid.Column="2" Clicked="DemoteButton_Clicked" />
                    <Button Text="➡" Grid.Column="3" Clicked="MoveButton_OnClicked" />
                </Grid>
            </ViewCell>
        </DataTemplate>
    </ContentPage.Resources>
    <RelativeLayout>
        <esriUI:MapView x:Name="MyMapView" Style="{StaticResource MapWithFormStyle}"
                        BindingContext="{x:Reference Name=ResponsiveFormContainer}" />
        <resources:ResponsiveFormContainer x:Name="ResponsiveFormContainer">
            <StackLayout>
                <Label Text="Use the buttons to re-arrange layers." />
                <Label Text="Layers in map"
                       FontAttributes="Bold"
                       HorizontalTextAlignment="Center" />
                <!-- Item template defined in UserControl.Resources above specifies that each listbox 
                     item's content consists of a label with the layer's Name and three buttons. -->
                <ListView x:Name="IncludedListView"
                          VerticalOptions="Start"
                          HeightRequest="80"
                          ItemTemplate="{StaticResource LayerListTemplate}" />
                <Label Text="Layers not in map"
                       FontAttributes="Bold"
                       HorizontalTextAlignment="Center" />
                <!-- Item template defined in UserControl.Resources above specifies that each listbox 
                     item's content consists of a label with the layer's Name and three buttons. -->
                <ListView x:Name="ExcludedListView"
                          VerticalOptions="Start"
                          HeightRequest="80"
                          ItemTemplate="{StaticResource LayerListTemplate}" />
            </StackLayout>
        </resources:ResponsiveFormContainer>
    </RelativeLayout>
</ContentPage>
// Copyright 2019 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.Mapping;
using System;
using Xamarin.Forms;

namespace ArcGISRuntimeXamarin.Samples.ManageOperationalLayers
{
    [ArcGISRuntime.Samples.Shared.Attributes.Sample(
        "Manage operational layers",
        "Map",
        "Add, remove, and reorder operational layers in a map.",
        "")]
    public partial class ManageOperationalLayers : ContentPage
    {
        private MapViewModel _viewModel;

        // Some URLs of layers to add to the map.
        private readonly string[] _layerUrls = new[]
        {
            "http://sampleserver5.arcgisonline.com/arcgis/rest/services/Elevation/WorldElevations/MapServer",
            "http://sampleserver5.arcgisonline.com/arcgis/rest/services/Census/MapServer",
            "http://sampleserver5.arcgisonline.com/arcgis/rest/services/DamageAssessment/MapServer"
        };

        public ManageOperationalLayers()
        {
            InitializeComponent();
            Initialize();
        }

        private void Initialize()
        {
            // Set up the view model and bindings.
            _viewModel = new MapViewModel(new Map(Basemap.CreateStreets()));
            MyMapView.Map = _viewModel.Map;
            IncludedListView.ItemsSource = _viewModel.IncludedLayers;
            ExcludedListView.ItemsSource = _viewModel.ExcludedLayers;

            // Add the layers.
            foreach (string layerUrl in _layerUrls)
            {
                _viewModel.AddLayerFromUrl(layerUrl);
            }
        }

        private void MoveButton_OnClicked(object sender, EventArgs e)
        {
            try
            {
                // Get the clicked button.
                Button clickedButton = (Button) sender;

                // Get the clicked layer.
                Layer clickedLayer = (Layer) clickedButton.BindingContext;

                // Move the layer.
                _viewModel.MoveLayer(clickedLayer);
            }
            // Sometimes if the user clicks too quickly NREs will occur.
            catch (Exception exception)
            {
                Console.WriteLine(exception);
            }
        }

        private void DemoteButton_Clicked(object sender, EventArgs e)
        {
            try
            {
                // Get the clicked button.
                Button clickedButton = (Button) sender;

                // Get the clicked layer.
                Layer clickedLayer = (Layer) clickedButton.BindingContext;

                // Move the layer.
                _viewModel.DemoteLayer(clickedLayer);
            }
            // Sometimes if the user clicks too quickly NREs will occur.
            catch (Exception exception)
            {
                Console.WriteLine(exception);
            }
        }

        private void PromoteButton_Clicked(object sender, EventArgs e)
        {
            try
            {
                // Get the clicked button.
                Button clickedButton = (Button) sender;

                // Get the clicked layer.
                Layer clickedLayer = (Layer) clickedButton.BindingContext;

                // Move the layer.
                _viewModel.PromoteLayer(clickedLayer);
            }
            // Sometimes if the user clicks too quickly NREs will occur.
            catch (Exception exception)
            {
                Console.WriteLine(exception);
            }
        }
    }

    class MapViewModel
    {
        public Map Map { get; }
        public LayerCollection IncludedLayers => Map.OperationalLayers;
        public LayerCollection ExcludedLayers { get; } = new LayerCollection();

        public MapViewModel(Map map)
        {
            Map = map;
        }

        public void AddLayerFromUrl(string layerUrl)
        {
            ArcGISMapImageLayer layer = new ArcGISMapImageLayer(new Uri(layerUrl));
            Map.OperationalLayers.Add(layer);
        }

        public void DemoteLayer(Layer selectedLayer)
        {
            // Find the collection the layer is in.
            LayerCollection owningCollection;
            if (IncludedLayers.Contains(selectedLayer))
            {
                owningCollection = IncludedLayers;
            }
            else
            {
                owningCollection = ExcludedLayers;
            }

            // Get the current index (position) of the layer.
            int layerIndex = owningCollection.IndexOf(selectedLayer);

            // Skip if the layer can't be moved down because it is already at the bottom.
            if (layerIndex == owningCollection.Count - 1)
            {
                return;
            }

            // Move the layer by removing it and re-adding it at its old position plus 1.
            owningCollection.Remove(selectedLayer);
            owningCollection.Insert(layerIndex + 1, selectedLayer);
        }

        public void PromoteLayer(Layer selectedLayer)
        {
            // Find the collection the layer is in.
            LayerCollection owningCollection = IncludedLayers.Contains(selectedLayer) ? IncludedLayers : ExcludedLayers;

            // Get the current index (position) of the layer.
            int layerIndex = owningCollection.IndexOf(selectedLayer);

            // Skip if the layer can't be moved because it is already at the top.
            if (layerIndex < 1)
            {
                return;
            }

            // Move the layer by removing it and re-adding it at its old position minus 1.
            owningCollection.Remove(selectedLayer);
            owningCollection.Insert(layerIndex - 1, selectedLayer);
        }

        public void MoveLayer(Layer selectedLayer)
        {
            // Remove the layer from the list it is currently in and add it to the other list.
            if (IncludedLayers.Contains(selectedLayer))
            {
                IncludedLayers.Remove(selectedLayer);
                ExcludedLayers.Add(selectedLayer);
            }
            else
            {
                ExcludedLayers.Remove(selectedLayer);
                IncludedLayers.Add(selectedLayer);
            }
        }
    }
}