WMS service catalog

View inAndroidFormsUWPWPFWinUIiOSView on GitHub

Connect to a WMS service and show the available layers and sublayers.

Image of WMS service catalog

Use case

WMS services often contain many layers and sublayers. Presenting the layers and sublayers in a UI allows you to explore what is available in the service and add individual layers to a map.

How to use the sample

  1. Open the sample. A hierarchical list of layers and sublayers will appear.
  2. Select a layer to enable it for display. If the layer has any children, the children will also be selected.

How it works

  1. A WmsService is created and loaded.
  2. WmsService has a ServiceInfo property, which is a WmsServiceInfo. WmsServiceInfo has a WmsLayerInfo object for each layer (excluding sublayers) in the LayerInfos collection.
  3. A method is called to recursively discover sublayers for each layer. Layers are wrapped in a view model and added to a list.
    • The view model has a Select method which recursively selects or deselects itself and sublayers.
    • The view model tracks the children and parent of each layer.
  4. Once the layer selection has been updated, another method is called to create a new WmsLayer from a list of selected WmsLayerInfo.

Relevant API

  • WmsLayer(List)
  • WmsLayerInfo
  • WmsService
  • WmsServiceInfo

About the data

This sample shows forecasts guidance warnings from an ArcGIS REST service produced by the U.S. National Weather Service. The map shows fronts, highs, and lows, as well as areas of forecast precipitation.

Tags

catalog, OGC, web map service, WMS

Sample Code

WmsServiceCatalog.cs
Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
// Copyright 2017 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 Android.App;
using Android.OS;
using Android.Views;
using Android.Widget;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Ogc;
using Esri.ArcGISRuntime.UI.Controls;
using System;
using System.Collections.Generic;
using System.Linq;

namespace ArcGISRuntime.Samples.WmsServiceCatalog
{
    [Activity(ConfigurationChanges = Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.ScreenSize)]
    [ArcGISRuntime.Samples.Shared.Attributes.Sample(
        name: "WMS service catalog",
        category: "Layers",
        description: "Connect to a WMS service and show the available layers and sublayers. ",
        instructions: "",
        tags: new[] { "OGC", "WMS", "catalog", "web map service" })]
    public class WmsServiceCatalog : Activity
    {
        // Create and hold reference to the used MapView
        private MapView _myMapView;

        // Hold a reference to the ListView
        private ListView _myDisplayList;

        // Hold the URL to the WMS service providing the US NOAA National Weather Service forecast weather chart
        private readonly Uri _wmsUrl = new Uri("https://idpgis.ncep.noaa.gov/arcgis/services/NWS_Forecasts_Guidance_Warnings/natl_fcst_wx_chart/MapServer/WMSServer?request=GetCapabilities&service=WMS");

        // Hold a list of LayerDisplayVM; this is the ViewModel
        private readonly List<LayerDisplayVM> _viewModelList = new List<LayerDisplayVM>();

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            Title = "WMS service catalog";

            // Create the UI, setup the control references
            CreateLayout();

            // Initialize the map
            Initialize();
        }

        private void CreateLayout()
        {
            // Create a new vertical layout for the app
            LinearLayout layout = new LinearLayout(this) { Orientation = Orientation.Vertical };

            // Configuration for having the mapview and webview fill the screen.
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MatchParent,
                ViewGroup.LayoutParams.MatchParent,
                1.0f
            );

            // Create the list view
            _myDisplayList = new ListView(this) { LayoutParameters = layoutParams };

            // Create two help labels
            TextView promptLabel = new TextView(this) { Text = "Select a layer" };

            // Create the mapview.
            _myMapView = new MapView(this) { LayoutParameters = layoutParams };

            // Add the views to the layout
            layout.AddView(promptLabel);
            layout.AddView(_myMapView);
            layout.AddView(_myDisplayList);

            // Show the layout in the app
            SetContentView(layout);
        }

        private async void Initialize()
        {
            // Apply an imagery basemap to the map
            _myMapView.Map = new Map(BasemapStyle.ArcGISDarkGray);

            // Create the WMS Service
            WmsService service = new WmsService(_wmsUrl);

            try
            {
                // Load the WMS Service
                await service.LoadAsync();

                // Get the service info (metadata) from the service.
                WmsServiceInfo info = service.ServiceInfo;

                // Get the list of layer infos.
                foreach (var layerInfo in info.LayerInfos)
                {
                    LayerDisplayVM.BuildLayerInfoList(new LayerDisplayVM(layerInfo, null), _viewModelList);
                }

                // Create an array adapter for the layer display
                ArrayAdapter adapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleSpinnerItem, _viewModelList);

                // Apply the adapter
                _myDisplayList.Adapter = adapter;

                // Subscribe to selection change notifications
                _myDisplayList.ItemClick += _myDisplayList_ItemClick;

                // Update the map display based on the viewModel
                UpdateMapDisplay(_viewModelList);
            }
            catch (Exception e)
            {
                new AlertDialog.Builder(this).SetMessage(e.ToString()).SetTitle("Error").Show();
            }
        }

        /// <summary>
        /// Updates the map with the latest layer selection
        /// </summary>
        private async void UpdateMapDisplay(List<LayerDisplayVM> displayList)
        {
            // Remove all existing layers
            _myMapView.Map.OperationalLayers.Clear();

            // Get a list of selected LayerInfos
            List<WmsLayerInfo> selectedLayers = displayList.Where(vm => vm.IsEnabled).Select(vm => vm.Info).ToList();

            // Only WMS layer infos without sub layers can be used to construct a WMS layer. Group layers that have sub layers must be excluded.
            selectedLayers = selectedLayers.Where(info => info.LayerInfos.Count == 0).ToList();

            // Return if list is empty
            if (!selectedLayers.Any())
            {
                return;
            }

            // Create a new WmsLayer from the selected layers
            WmsLayer myLayer = new WmsLayer(selectedLayers);

            try
            {
                // Load the layer
                await myLayer.LoadAsync();

                // Zoom to the extent of the layer
                _myMapView.SetViewpoint(new Viewpoint(myLayer.FullExtent));

                // Add the layer to the map
                _myMapView.Map.OperationalLayers.Add(myLayer);
            }
            catch (Exception e)
            {
                new AlertDialog.Builder(this).SetMessage(e.ToString()).SetTitle("Error").Show();
            }
        }

        /// <summary>
        /// Takes action once a new layer selection is made
        /// </summary>
        private void _myDisplayList_ItemClick(object sender, AdapterView.ItemClickEventArgs e)
        {
            // Clear existing selection
            foreach (LayerDisplayVM item in _viewModelList)
            {
                item.Select(false);
            }

            // Update the selection
            _viewModelList[e.Position].Select();

            // Update the map
            UpdateMapDisplay(_viewModelList);
        }
    }

    /// <summary>
    /// This is a ViewModel class for maintaining the state of a layer selection.
    /// Typically, this would go in a separate file, but it is included here for clarity.
    /// </summary>
    public class LayerDisplayVM
    {
        public WmsLayerInfo Info { get; }

        // True if layer is selected for display.
        public bool IsEnabled { get; private set; }

        // Keeps track of how much indentation should be added (to simulate a tree view in a list).
        private int NestLevel
        {
            get
            {
                if (Parent == null)
                {
                    return 0;
                }

                return Parent.NestLevel + 1;
            }
        }

        private List<LayerDisplayVM> Children { get; set; }

        private LayerDisplayVM Parent { get; }

        public LayerDisplayVM(WmsLayerInfo info, LayerDisplayVM parent)
        {
            Info = info;
            Parent = parent;
        }

        // Select this layer and all child layers.
        public void Select(bool isSelected = true)
        {
            IsEnabled = isSelected;
            if (Children == null)
            {
                return;
            }

            foreach (var child in Children)
            {
                child.Select(isSelected);
            }
        }

        // Format with indentation to simulate a treeview.
        public override string ToString()
        {
            return $"{new String(' ', NestLevel * 8)} {Info.Title}";
        }

        public static void BuildLayerInfoList(LayerDisplayVM root, IList<LayerDisplayVM> result)
        {
            // Add the root node to the result list.
            result.Add(root);

            // Initialize the child collection for the root.
            root.Children = new List<LayerDisplayVM>();

            // Recursively add sublayers.
            foreach (WmsLayerInfo layer in root.Info.LayerInfos)
            {
                // Create the view model for the sublayer.
                LayerDisplayVM layerVM = new LayerDisplayVM(layer, root);

                // Add the sublayer to the root's sublayer collection.
                root.Children.Add(layerVM);

                // Recursively add children.
                BuildLayerInfoList(layerVM, result);
            }
        }
    }
}

Your browser is no longer supported. Please upgrade your browser for the best experience. See our browser deprecation post for more details.