Skip to content
View inMAUIWPFWinUIView on GitHub

Apply map algebra to an elevation raster to floor, mask, and categorize the elevation values into discrete integer-based categories.

Apply map algebra sample

Use case

Categorizing raster data, such as elevation values, into distinct categories is a common spatial analysis workflow. This often involves applying threshold‑based logic or algebraic expressions to transform continuous numeric fields into discrete, integer‑based categories suitable for downstream analytical or computational operations. These operations can be specified and applied using map algebra.

How to use the sample

When the sample opens, it displays the source elevation raster. Select the Categorize button to generate a raster with three distinct ice age related geomorphological categories (raised shore line areas in blue, ice free high ground in brown and areas covered by ice in teal). After processing completes, use the radio buttons to switch between the map algebra results raster and the original elevation raster.

How it works

  1. Create a ContinuousField from a raster file using ContinuousField.CreateAsync.
  2. Create a ContinuousFieldFunction from the continuous field and mask values below sea level using IsGreaterThanOrEqualTo.
  3. Round elevation values down to the lowest 10-meter interval with map algebra operators ((continuousFieldFunction / 10).Floor() * 10), and then convert the result to a DiscreteFieldFunction with ToDiscreteFieldFunction.
  4. Create BooleanFieldFunctions for each category by defining a range with map algebra operators such as IsGreaterThanOrEqualTo, LogicalAnd, and IsLessThan.
  5. Create a new DiscreteField by chaining ReplaceIf operations into discrete category values and evaluating the result with EvaluateAsync.
  6. Export the discrete field to files with ExportToFilesAsync and create a Raster with the result. Use it to create a RasterLayer.
  7. Apply a ColormapRenderer to the raster and display it in the map view.

Relevant API

  • BooleanFieldFunction
  • ColormapRenderer
  • ColorRamp
  • ContinuousField
  • ContinuousFieldFunction
  • DiscreteField
  • DiscreteFieldFunction
  • MinMaxStretchParameters
  • Raster
  • RasterLayer
  • StretchRenderer

Offline data

This sample downloads the following items from ArcGIS Online automatically:

About the data

The elevation raster of the Isle of Arran, Scotland is a 10m resolution digital terrain model. (Data Copyright Scottish Government and SEPA (2014)).

Tags

elevation, map algebra, raster, spatial analysis, terrain

Sample Code

ApplyMapAlgebra.xaml.csApplyMapAlgebra.xaml.csApplyMapAlgebra.xaml
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
// Copyright 2026 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.Samples.Managers;
using Esri.ArcGISRuntime.Analysis;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Rasters;
using System;
using System.Drawing;
using System.IO;
using System.Threading.Tasks;

namespace ArcGIS.Samples.ApplyMapAlgebra
{
    [ArcGIS.Samples.Shared.Attributes.Sample(
        name: "Apply map algebra",
        category: "Analysis",
        description: "Apply map algebra to an elevation raster to floor, mask, and categorize the elevation values into discrete integer-based categories.",
        instructions: "When the sample opens, it displays the source elevation raster. Select the **Categorize** button to generate a raster with three distinct ice age related geomorphological categories (raised shore line areas in blue, ice free high ground in brown and areas covered by ice in teal). After processing completes, use the radio buttons to switch between the map algebra results raster and the original elevation raster.",
        tags: new[] { "elevation", "map algebra", "raster", "spatial analysis", "terrain" })]
    [ArcGIS.Samples.Shared.Attributes.OfflineData("aa97788593e34a32bcaae33947fdc271")]
    public partial class ApplyMapAlgebra : ContentPage
    {
        private RasterLayer _elevationRasterLayer;
        private RasterLayer _geomorphicRasterLayer;
        private ContinuousField _elevationField;
        private DiscreteField _geomorphicCategoryField;

        public ApplyMapAlgebra()
        {
            InitializeComponent();
            _ = Initialize();
        }

        private async Task Initialize()
        {
            // Create a map with a dark hillshade basemap and set the initial viewpoint to the Isle of Arran, Scotland.
            MyMapView.Map = new Map(BasemapStyle.ArcGISHillshadeDark)
            {
                InitialViewpoint = new Viewpoint(55.584612, -5.234218, 300000)
            };

            try
            {
                // Get the path to the locally stored elevation raster file.
                string rasterPath = DataManager.GetDataFolder("aa97788593e34a32bcaae33947fdc271", "arran.tif");

                // Create a continuous field from the elevation raster file.
                _elevationField = await ContinuousField.CreateAsync(new[] { rasterPath }, 0);

                // Display the source elevation raster on the map.
                DisplayElevationRaster(rasterPath);

                // Enable the categorize button once the data is loaded.
                CategorizeButton.IsEnabled = true;
            }
            catch (Exception ex)
            {
                await Application.Current.Windows[0].Page.DisplayAlert("Error", ex.Message, "OK");
            }
        }

        private void DisplayElevationRaster(string rasterPath)
        {
            // Create a raster layer from the elevation raster file.
            _elevationRasterLayer = new RasterLayer(new Raster(rasterPath));

            // Create a stretch renderer to visualize the elevation raster layer using the surface preset color ramp.
            _elevationRasterLayer.Renderer = new StretchRenderer(
                new MinMaxStretchParameters(new[] { 0.0 }, new[] { 874.0 }),
                gammas: new[] { 1.0 },
                estimateStatistics: false,
                colorRamp: ColorRamp.Create(PresetColorRampType.Surface, 256));

            // Set opacity to allow the basemap hillshade to show through.
            _elevationRasterLayer.Opacity = 0.5;

            // Add the elevation raster layer to the map.
            MyMapView.Map.OperationalLayers.Add(_elevationRasterLayer);
        }

        private async Task CreateGeomorphicCategoryField()
        {
            // Create a continuous field function from the elevation field.
            var continuousFieldFunction = ContinuousFieldFunction.Create(_elevationField);

            // Mask out values below sea level to categorize only land.
            var elevationFieldFunction = continuousFieldFunction.Mask(
                continuousFieldFunction.IsGreaterThanOrEqualTo(0));

            // Round elevation values down to the lower 10 m interval, then convert to a discrete field function.
            var tenMeterBinField = ((elevationFieldFunction / 10).Floor() * 10).ToDiscreteFieldFunction();

            // Create boolean fields for each geomorphic category based on the nearest 10 m interval field.
            var isRaisedShoreline = tenMeterBinField.IsGreaterThanOrEqualTo(0)
                .LogicalAnd(tenMeterBinField.IsLessThan(10));

            // Operator overloads (>=, <, &) can be used in place of IsGreaterThanOrEqualTo, IsLessThan, and LogicalAnd.
            var isIceCovered = (tenMeterBinField >= 10) & (tenMeterBinField < 600);

            var isIceFreeHighGround = tenMeterBinField.IsGreaterThanOrEqualTo(600);

            // Assign geomorphic categories based on the boolean fields:
            // raised shoreline = 1, ice covered = 2, ice-free high ground = 3.
            _geomorphicCategoryField = await tenMeterBinField
                .ReplaceIf(isRaisedShoreline, 1)
                .ReplaceIf(isIceCovered, 2)
                .ReplaceIf(isIceFreeHighGround, 3)
                .EvaluateAsync();
        }

        private async void OnCategorizeClicked(object sender, EventArgs e)
        {
            CategorizeButton.IsEnabled = false;
            CategorizeButton.Text = "Map algebra computing...";

            try
            {
                // Build and evaluate the map algebra expression to generate the geomorphic category field.
                await CreateGeomorphicCategoryField();
            }
            catch (Exception ex)
            {
                await Application.Current.Windows[0].Page.DisplayAlert("Error creating geomorphic category field", ex.Message, "OK");
                CategorizeButton.IsEnabled = true;
                CategorizeButton.Text = "Categorize";
                return;
            }

            try
            {
                // Export the discrete field to a temporary folder.
                string tempDir = Path.Combine(Path.GetTempPath(), "geomorphic_temp_files");
                Directory.CreateDirectory(tempDir);

                // Clean up any previously exported files.
                const string filenamesPrefix = "geomorphicCategorization";
                foreach (string file in Directory.GetFiles(tempDir, $"{filenamesPrefix}*"))
                    File.Delete(file);

                // Export the discrete field result to a raster file.
                var exportedFiles = await _geomorphicCategoryField.ExportToFilesAsync(tempDir, filenamesPrefix);

                if (exportedFiles.Count == 0 || !File.Exists(exportedFiles[0]))
                {
                    await Application.Current.Windows[0].Page.DisplayAlert("Export Error", "Exported geomorphic categorization file does not exist.", "OK");
                    CategorizeButton.IsEnabled = true;
                    CategorizeButton.Text = "Categorize";
                    return;
                }

                // Display the geomorphic categories on the map.
                DisplayGeomorphicCategories(exportedFiles[0]);

                // Show the layer toggle controls and hide the categorize button.
                CategorizeButton.IsVisible = false;
                LayerTogglePanel.IsVisible = true;
                GeomorphicRadioButton.IsChecked = true;
                UpdateVisibleRasterLayer();
            }
            catch (Exception ex)
            {
                await Application.Current.Windows[0].Page.DisplayAlert("Error exporting geomorphic categorization", ex.Message, "OK");
                CategorizeButton.IsEnabled = true;
                CategorizeButton.Text = "Categorize";
            }
        }

        private void DisplayGeomorphicCategories(string rasterFilePath)
        {
            // Create a raster layer from the exported geomorphic categorization file.
            _geomorphicRasterLayer = new RasterLayer(new Raster(rasterFilePath));

            // Create an array of colors for the geomorphic categories.
            // The array index maps directly to the pixel value in the raster.
            var colors = new System.Drawing.Color[]
            {
                System.Drawing.Color.Transparent,              // 0 = no category (NoData pixels are hidden)
                System.Drawing.Color.FromArgb(25, 118, 210),   // 1 = raised shoreline - blue
                System.Drawing.Color.FromArgb(128, 203, 196),  // 2 = ice covered - teal
                System.Drawing.Color.FromArgb(121, 85, 72),    // 3 = ice-free high ground - brown
            };

            // Create a colormap renderer to assign colors to pixel values and apply it to the raster layer.
            _geomorphicRasterLayer.Renderer = new ColormapRenderer(colors);

            // Set opacity to allow the basemap hillshade to show through.
            _geomorphicRasterLayer.Opacity = 0.5;

            // Add the geomorphic categorization raster layer to the map.
            MyMapView.Map.OperationalLayers.Add(_geomorphicRasterLayer);
        }

        private void OnRasterLayerSelectionChanged(object sender, CheckedChangedEventArgs e)
        {
            UpdateVisibleRasterLayer();
        }

        private void UpdateVisibleRasterLayer()
        {
            if (_elevationRasterLayer == null) return;
            bool showGeomorphic = GeomorphicRadioButton.IsChecked;
            _elevationRasterLayer.IsVisible = !showGeomorphic;
            if (_geomorphicRasterLayer != null)
                _geomorphicRasterLayer.IsVisible = showGeomorphic;
        }
    }
}

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