Skip to content

Identify raster cell

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 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 an area of the raster to identify it and see the raw raster cell information displayed in a callout. Tap and hold to see a magnifier and the cell information updated dynamically as you drag.

How it works

  1. Get the screen point on the map where a user tapped or long pressed and dragged from the MapView.
  2. On tap or long press drag:
  • Call MapViewProxy.identify(on:screenPoint:tolerance:returnPopupsOnly:maximumResults:) passing in the screen point, tolerance, and maximum number of results per layer.
  • Await the result of the identify and then get the GeoElement from the layer result.
  • Create a callout at the calculated map point and populate the callout content with text from the RasterCell.attributes.

Relevant API

  • GeoViewProxy
  • IdentifyLayerResult
  • RasterCell
  • RasterCell.attributes
  • RasterLayer

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

IdentifyRasterCellView.swift
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 // Copyright 2023 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 // // https://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.  import ArcGIS import SwiftUI  struct IdentifyRasterCellView: View {  /// The view model for the sample.  @StateObject private var model = Model()   /// The screen point of where the user tapped.  @State private var tapScreenPoint: CGPoint?   var body: some View {  MapViewReader { mapViewProxy in  MapView(map: model.map)  .callout(placement: $model.calloutPlacement  .animation(model.calloutShouldOffset ? nil : .default.speed(2))  ) { _ in  Text(model.calloutText)  .font(.callout)  .padding(8)  }  .onSingleTapGesture { screenPoint, _ in  tapScreenPoint = screenPoint  }  .onLongPressAndDragGesture { screenPoint in  model.calloutShouldOffset = true  tapScreenPoint = screenPoint  } onEnded: {  model.calloutShouldOffset = false  }  .task(id: EquatablePair(tapScreenPoint, model.calloutShouldOffset)) {  // Create a callout at the tap location.  if let tapScreenPoint {  await model.callout(at: tapScreenPoint, using: mapViewProxy)  }  }  .errorAlert(presentingError: $model.error)  }  } }  private extension IdentifyRasterCellView {  /// The view model for the sample.  @MainActor  class Model: ObservableObject {  /// A map with a raster layer and an oceans basemap centered on Cape Town, South Africa.  private(set) lazy var map: Map = {  let map = Map(basemapStyle: .arcGISOceans)  map.initialViewpoint = Viewpoint(latitude: -34.1, longitude: 18.6, scale: 1_155e3)  map.addOperationalLayer(rasterLayer)  return map  }()   /// The map's raster layer loaded from a local URL.  private let rasterLayer = RasterLayer(raster: Raster(fileURL: .ndviRaster))   /// The placement of the callout on the map.  @Published var calloutPlacement: CalloutPlacement?   /// The text shown on the callout.  @Published private(set) var calloutText: String = ""   /// A Boolean value that indicates whether the callout placement should be offsetted for the map magnifier.  @Published var calloutShouldOffset = false   /// The error shown in the error alert.  @Published var error: Error?   /// Creates a callout displaying the data of a raster cell at a given screen point.  /// - Parameters:  /// - screenPoint: The screen point of the raster cell at which to place the callout.  /// - mapViewProxy: The proxy used to handle the screen point.  func callout(at screenPoint: CGPoint, using proxy: MapViewProxy) async {  // Get the raster cell for the screen point using the map view proxy.  if let rasterCell = await rasterCell(at: screenPoint, using: proxy) {  // Update the callout text and placement.  updateCalloutText(using: rasterCell)  updateCalloutPlacement(to: screenPoint, using: proxy)  } else {  // Dismiss the callout if no raster cell was found, e.g. tap was not on layer.  calloutPlacement = nil  }  }   /// Identifies the raster cell for a given screen point on the raster layer.  /// - Parameters:  /// - screenPoint: The screen point corresponding to a raster cell.  /// - proxy: The proxy used to identify the screen point on the raster layer.  /// - Returns: The first raster cell found in the identify result.  private func rasterCell(at screenPoint: CGPoint, using proxy: MapViewProxy) async -> RasterCell? {  do {  // Identify the screen point on the raster layer using the map view proxy.  let identifyResult = try await proxy.identify(on: rasterLayer, screenPoint: screenPoint, tolerance: 1)   // Get the first raster cell from the identify result.  let rasterCell = identifyResult.geoElements.first(where: { $0 is RasterCell })  return rasterCell as? RasterCell  } catch {  self.error = error  return nil  }  }   /// Updates the location of the callout placement to a given screen point.  /// - Parameters:  /// - screenPoint: The screen point at which to place the callout.  /// - proxy: The proxy used to convert the screen point to a map point.  private func updateCalloutPlacement(to screenPoint: CGPoint, using proxy: MapViewProxy) {  // Create an offset to offset the callout if needed, e.g. the magnifier is showing.  let offset = calloutShouldOffset ? CGPoint(x: 0, y: -70) : .zero   // Get the map location of the screen point from the map view proxy.  if let location = proxy.location(fromScreenPoint: screenPoint) {  calloutPlacement = .location(location, offset: offset)  }  }   /// Updates the text shown in the callout using the attributes and coordinates of a given raster cell.  /// - Parameter cell: The raster cell to create the text from.  private func updateCalloutText(using cell: RasterCell) {  // Create the attributes text using the attributes of the raster cell.  let attributes = cell.attributes  .map { "\($0.key): \($0.value)" }  .sorted(by: >)  .joined(separator: "\n")   // Create the coordinate texts using the extent of the cell's geometry.  guard let extent = cell.geometry?.extent else {  calloutText = attributes  return  }  let roundedStyle = FloatingPointFormatStyle<Double>.number.rounded(rule: .awayFromZero, increment: 0.001)  let xCoordinate = "X: \(extent.xMin.formatted(roundedStyle))"  let yCoordinate = "Y: \(extent.yMin.formatted(roundedStyle))"   // Update the callout text.  calloutText = "\(attributes)\n\n\(xCoordinate)\n\(yCoordinate)"  }  }   // A generic struct made up of two equatable types.  struct EquatablePair<T: Equatable, U: Equatable>: Equatable {  var t: T  var u: U   init(_ t: T, _ u: U) {  self.t = t  self.u = u  }  } }  private extension MapView {  /// Sets a closure to perform when the map view recognizes a long press and drag gesture.  /// - Parameters:  /// - action: The closure to perform when the gesture is recognized.  /// - onEnded: The closure to perform when the long press or drag ends.  /// - Returns: A new `View` object.  func onLongPressAndDragGesture(  perform action: @escaping (CGPoint) -> Void,  onEnded: @escaping () -> Void  ) -> some View {  self  .onLongPressGesture { screenPoint, _ in  action(screenPoint)  }  .gesture(  LongPressGesture()  .simultaneously(with: DragGesture())  .onEnded { value in  // Run the closure if there was a valid long press with the drag.  if value.first != nil {  onEnded()  }  }  )  } }  private extension URL {  /// A URL to the local NDVI classification raster file.  static var ndviRaster: Self {  Bundle.main.url(forResource: "SA_EVI_8Day_03May20", withExtension: "tif", subdirectory: "SA_EVI_8Day_03May20")!  } }

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