Identify raster cell

View inWPFUWPFormsiOSAndroid
View on GitHub

Get the cell value of a local raster at the tapped location and display the result in a callout.

Image of identify raster cell

Use case

You may want to identify a raster layer to get its exact cell value in the case the approximate value conveyed by its symbology is not sufficient. The information available for the raster cell depends on the type of raster layer being identified. For example, a 3-band satellite or aerial image might provide 8-bit RGB values, whereas a digital elevation model (DEM) would provide floating point z values. By identifying a raster cell of a DEM, you can retrieve the precise elevation of a location.

How to use the sample

Tap or move your cursor over an area of the raster to identify a raster cell and display it's attributes in a callout.

How it works

  1. Create a GeoViewTapped event on the MapView.
  2. On tap:
  3. Call IdentifyLayerAsync passing in the screen point, tolerance, and maximum number of results per layer.
  4. Await the result of the identify and then get the GeoElement from the layer result.
  5. Create a callout at the calculated map point and populate the callout content with text from the RasterCell attributes.

Relevant API

  • GeoView.IdentifyLayerAsync
  • IdentifyLayerResult
  • RasterCell
  • RasterCell.Attributes
  • RasterLayer

Offline data

This sample uses MODIS raster imagery. Data is downloaded from ArcGIS Online automatically.

About the data

The data shown is an NDVI classification derived from MODIS imagery between 27 Apr 2020 and 4 May 2020. It comes from the NASA Worldview application. In a normalized difference vegetation index, or NDVI, values range between -1 and +1 with the positive end of the spectrum showing green vegetation.

Tags

band, cell, cell value, continuous, discrete, identify, NDVI, pixel, pixel value, raster

Sample Code

IdentifyRasterCell.cs
                                                                                                                                                                                                  
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
// Copyright 2020 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 ArcGISRuntime;
using ArcGISRuntime.Samples.Managers;
using Esri.ArcGISRuntime.Data;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Rasters;
using Esri.ArcGISRuntime.UI.Controls;
using Foundation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UIKit;

namespace ArcGISRuntimeXamarin.Samples.IdentifyRasterCell
{
    [Register("IdentifyRasterCell")]
    [ArcGISRuntime.Samples.Shared.Attributes.Sample(
        name: "Identify raster cell",
        category: "Layers",
        description: "Get the cell value of a local raster at the tapped location and display the result in a callout.",
        instructions: "Tap or move your cursor over an area of the raster to identify a raster cell and display it's attributes in a callout.",
        tags: new[] { "NDVI", "band", "cell", "cell value", "continuous", "discrete", "identify", "pixel", "pixel value", "raster" })]
    [ArcGISRuntime.Samples.Shared.Attributes.OfflineData("b5f977c78ec74b3a8857ca86d1d9b318")]
    public class IdentifyRasterCell : UIViewController
    {
        // Hold references to UI controls.
        private MapView _myMapView;

        // Raster layer to display raster data on the map.
        private RasterLayer _rasterLayer;

        public IdentifyRasterCell()
        {
            Title = "Identify raster cell";
        }

        private async void Initialize()
        {
            // Define a new map with Wgs84 Spatial Reference.
            var map = new Map(BasemapType.Oceans, latitude: -34.1, longitude: 18.6, levelOfDetail: 9);

            // Get the file name for the raster.
            string filepath = DataManager.GetDataFolder("b5f977c78ec74b3a8857ca86d1d9b318", "SA_EVI_8Day_03May20.tif");

            // Load the raster file.
            var raster = new Raster(filepath);

            // Initialize the raster layer.
            _rasterLayer = new RasterLayer(raster);

            // Add the raster layer to the map.
            map.OperationalLayers.Add(_rasterLayer);

            // Add map to the map view.
            _myMapView.Map = map;

            try
            {
                // Wait for the layer to load.
                await _rasterLayer.LoadAsync();

                // Set the viewpoint.
                await _myMapView.SetViewpointGeometryAsync(_rasterLayer.FullExtent);
            }
            catch (Exception ex)
            {
                new UIAlertView(ex.GetType().Name, ex.Message, (IUIAlertViewDelegate)null, "OK", null).Show();
            }
        }

        private async void MapTapped(object sender, GeoViewInputEventArgs e)
        {
            try
            {
                // Get the result for where the user tapped on the raster layer.
                IdentifyLayerResult identifyResult = await _myMapView.IdentifyLayerAsync(_rasterLayer, e.Position, 1, false, 1);

                // If no cell was identified, dismiss the callout.
                if (!identifyResult.GeoElements.Any())
                {
                    _myMapView.DismissCallout();
                    return;
                }

                // Create a StringBuilder to display information to the user.
                var stringBuilder = new StringBuilder();

                // Get the identified raster cell.
                GeoElement cell = identifyResult.GeoElements.First();

                // Loop through the attributes (key/value pairs).
                foreach (KeyValuePair<string, object> keyValuePair in cell.Attributes)
                {
                    // Add the key/value pair to the string builder.
                    stringBuilder.AppendLine($"{keyValuePair.Key}: {keyValuePair.Value}");
                }

                // Get the x and y values of the cell.
                double x = cell.Geometry.Extent.XMin;
                double y = cell.Geometry.Extent.YMin;

                // Add the X & Y coordinates where the user clicked raster cell to the string builder.
                stringBuilder.AppendLine($"X: {Math.Round(x, 4)}\nY: {Math.Round(y, 4)}");

                // Create a label using the string.
                var cellLabel = new UILabel
                {
                    Text = stringBuilder.ToString(),
                    TextAlignment = UITextAlignment.Center,
                    AdjustsFontSizeToFitWidth = false,
                    Font = UIFont.SystemFontOfSize(15),
                    TextColor = UIColor.Black,
                    Lines = 0,
                    TranslatesAutoresizingMaskIntoConstraints = false,
                    MinimumFontSize = 25
                };

                // Display the label in the map view.
                _myMapView.ShowCalloutAt(e.Location, cellLabel);
            }
            catch (Exception ex)
            {
                new UIAlertView(ex.GetType().Name, ex.Message, (IUIAlertViewDelegate)null, "OK", null).Show();
            }
        }

        public override void LoadView()
        {
            // Create the views.
            View = new UIView { BackgroundColor = ApplicationTheme.BackgroundColor };

            _myMapView = new MapView();
            _myMapView.TranslatesAutoresizingMaskIntoConstraints = false;

            var instructionLabel = new UILabel
            {
                Text = "Tap to identify raster cell.",
                AdjustsFontSizeToFitWidth = true,
                TextAlignment = UITextAlignment.Center,
                BackgroundColor = UIColor.FromWhiteAlpha(0, .6f),
                TextColor = UIColor.White,
                Lines = 1,
                TranslatesAutoresizingMaskIntoConstraints = false
            };

            // Add the views.
            View.AddSubviews(_myMapView, instructionLabel);

            // Lay out the views.
            NSLayoutConstraint.ActivateConstraints(new[]{
                _myMapView.TopAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.TopAnchor),
                _myMapView.BottomAnchor.ConstraintEqualTo(View.BottomAnchor),
                _myMapView.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor),
                _myMapView.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor),

                instructionLabel.TopAnchor.ConstraintEqualTo(_myMapView.TopAnchor),
                instructionLabel.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor),
                instructionLabel.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor),
                instructionLabel.HeightAnchor.ConstraintEqualTo(40),
            });
        }

        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            Initialize();
        }

        public override void ViewWillAppear(bool animated)
        {
            base.ViewWillAppear(animated);

            // Subscribe to events.
            _myMapView.GeoViewTapped += MapTapped;
        }

        public override void ViewDidDisappear(bool animated)
        {
            base.ViewDidDisappear(animated);

            // Unsubscribe from events, per best practice.
            _myMapView.GeoViewTapped -= MapTapped;
        }
    }
}

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