Analyze terrain suitability from an elevation raster by deriving slope and aspect.

Use case
Terrain suitability analysis is a common way to narrow a larger elevation surface down to areas that match a specific set of conditions. Slope and aspect are derived from elevation datasets to show how steep the terrain is and which direction it faces. Both of these factors can determine whether an area is suitable for a given purpose, for example, finding areas which are more sheltered from weather versus areas with more exposed terrain.
How to use the sample
When the sample opens, the map shows the results of a preconfigured terrain suitability analysis which finds southward facing lowland slopes on the Isle of Arran, Scotland. The areas matching the criteria are rendered in green, and those not, in white. Open the settings panel to choose another preconfigured scenario, that of a west to north facing slope in upland terrains. Areas matching this criteria are rendered in purple.
How it works
- Create a
ContinuousFieldfrom a raster file. - Create a
ContinuousFieldFunctionfrom the continuous field. - Derive a
slopefunction and anaspectfunction from the continuous field function. - Create
BooleanFieldFunctionmasks for slope, aspect, and elevation using range checks with map algebra. - Combine the masks with
logicalAndand apply a land-only mask to exclude areas below sea level. - Convert the final result to a
DiscreteFieldFunction. - Create a
FieldAnalysisfrom the discrete field function. - Apply a
ColormapRendererwith a color for areas not matching the terrain suitability criteria, and a color for matching areas. - Add the analysis to an
AnalysisOverlay.
Relevant API
- AnalysisOverlay
- BooleanFieldFunction
- ColormapRenderer
- ContinuousField
- ContinuousFieldFunction
- DiscreteFieldFunction
- FieldAnalysis
About the data
The sample uses a 10m resolution digital terrain elevation raster of the Isle of Arran, Scotland (Data Copyright Scottish Government and SEPA (2014)).
Tags
aspect, elevation, field analysis, map algebra, raster, slope, spatial reference, terrain
Sample code
// 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//// 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 ArcGISimport SwiftUI
struct AnalyzeTerrainSuitabilityFromSlopeAndAspectView: View { /// The view model for the sample. @State private var model = Model() /// A Boolean value indicating whether the settings are showing. @State private var isShowingSettings = false /// The identifier for the currently displayed scenario toast. This is needed /// to trigger the toast dismissal task when the scenario changes. @State private var scenarioToastID: UUID? /// The error shown in the error alert. @State private var error: (any Error)?
var body: some View { MapView( map: model.map, viewpoint: model.viewpoint, analysisOverlays: [model.analysisOverlay] ) .onAnalysisViewStateChanged { analysis, viewState in guard let activeAnalysis = model.activeAnalysis, analysis === activeAnalysis else { return } if let analysisError = viewState.error { error = analysisError } } .overlay(alignment: .top) { if scenarioToastID != nil { Text(model.selectedScenario.description) .font(.footnote) .foregroundStyle(.secondary) .multilineTextAlignment(.center) .padding() .background(.regularMaterial) .clipShape(.rect(cornerRadius: 8)) .padding() .transition( .move(edge: .top).combined(with: .opacity) ) } } .overlay(alignment: .bottom) { Text( "Raster data copyright Scottish Government and SEPA (2014)" ) .font(.caption) .frame(maxWidth: .infinity) .padding(.vertical, 6) .background( .thinMaterial, ignoresSafeAreaEdges: .horizontal ) } .toolbar { ToolbarItem(placement: .bottomBar) { Button("Settings", systemImage: "gear") { isShowingSettings.toggle() } .popover(isPresented: $isShowingSettings) { TerrainSuitabilitySettings(model: model) .presentationCompactAdaptation(.popover) .frame(idealWidth: 320, idealHeight: 340) } } } .task { do { try await model.configureTerrainSuitabilityAnalyses() scenarioToastID = UUID() } catch { self.error = error } } .task(id: scenarioToastID) { guard scenarioToastID != nil else { return }
try? await Task.sleep(for: .seconds(3)) guard !Task.isCancelled else { return }
scenarioToastID = nil } .onChange(of: model.selectedScenario) { isShowingSettings = false scenarioToastID = UUID() } .animation(.default, value: scenarioToastID) .errorAlert(presentingError: $error) }}
extension AnalyzeTerrainSuitabilityFromSlopeAndAspectView { /// A view for selecting a terrain suitability scenario. struct TerrainSuitabilitySettings: View { /// The model containing the selected terrain suitability scenario. @Bindable var model: Model
var body: some View { NavigationStack { Form { Picker("Scenario", selection: $model.selectedScenario) { ForEach(SiteScenario.allCases) { scenario in Text(scenario.label) } } .pickerStyle(.inline) } .navigationTitle("Terrain Suitability") } } }}// 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//// 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 ArcGISimport UIKit
extension AnalyzeTerrainSuitabilityFromSlopeAndAspectView { /// The model that creates and manages the terrain suitability analyses. @MainActor @Observable final class Model { /// The WGS 84 UTM zone 30N spatial reference used by the elevation data /// and map. private static let utm30N = SpatialReference(wkid: WKID(32630)!)!
/// The map that displays the terrain suitability analyses. let map = Map(spatialReference: Model.utm30N) /// The viewpoint centered on the extent of the elevation data. var viewpoint: Viewpoint? /// The overlay containing the terrain suitability analyses. let analysisOverlay = AnalysisOverlay() /// A Boolean value indicating whether an analysis is being updated. var isUpdatingAnalysis = false
/// The analysis for gentle, lowland south-facing slopes. private var gentleSouthFacingSlopesAnalysis: FieldAnalysis? /// The analysis for steep, upland west- through north-facing slopes. private var steepWestAndNorthFacingSlopesAnalysis: FieldAnalysis? /// The scenario whose analysis is currently visible. var selectedScenario = SiteScenario.gentleSouthFacingSlopes { didSet { updateAnalysisVisibility() } }
/// The analysis associated with the selected scenario, if it has been /// created. var activeAnalysis: FieldAnalysis? { switch selectedScenario { case .gentleSouthFacingSlopes: gentleSouthFacingSlopesAnalysis case .steepWestAndNorthFacingSlopes: steepWestAndNorthFacingSlopesAnalysis } }
/// Creates the elevation field and terrain suitability analyses used by /// the sample. /// - Throws: An error if the elevation data cannot be accessed or used /// to create a field. func configureTerrainSuitabilityAnalyses() async throws { isUpdatingAnalysis = true defer { isUpdatingAnalysis = false }
// Project the Web Mercator raster into UTM30N because slope and // aspect require a conformal projection. let elevationField = try await ContinuousField.field( fromFilesAt: [try .terrainSuitabilityArranElevation()], bandIndex: 0, spatialReference: Self.utm30N ) let elevationFunction = ContinuousFieldSupplier( field: elevationField ) let inputs = TerrainAnalysisInputs( slopeFunction: elevationFunction.slope(), aspectFunction: elevationFunction.aspect(), elevationFunction: elevationFunction, aboveSeaLevelSelection: elevationFunction .isGreaterThanOrEqualTo(0) )
let gentleAnalysis = makeAnalysis( inputs: inputs, criteria: .gentleSouthFacingSlopes, color: .systemGreen ) let steepAnalysis = makeAnalysis( inputs: inputs, criteria: .steepWestAndNorthFacingSlopes, color: .systemPurple ) gentleSouthFacingSlopesAnalysis = gentleAnalysis steepWestAndNorthFacingSlopesAnalysis = steepAnalysis analysisOverlay.addAnalyses([ gentleAnalysis, steepAnalysis ]) updateAnalysisVisibility() viewpoint = Viewpoint( center: elevationField.extent.center, scale: 200_000 ) }
/// Updates the analyses so only the selected scenario is visible. private func updateAnalysisVisibility() { // Reset; MapView's analysis view state callback will set this to // true while the active analysis is updating. isUpdatingAnalysis = false gentleSouthFacingSlopesAnalysis?.isVisible = selectedScenario == .gentleSouthFacingSlopes steepWestAndNorthFacingSlopesAnalysis?.isVisible = selectedScenario == .steepWestAndNorthFacingSlopes }
/// Creates a field analysis that identifies cells matching a set of /// terrain criteria. /// - Parameters: /// - inputs: The elevation-derived field functions used to evaluate /// each cell. /// - criteria: The slope, aspect, and elevation ranges that define /// suitable terrain. /// - color: The color used to render cells that satisfy all criteria. /// - Returns: A hidden field analysis configured with the suitability /// function and renderer. private func makeAnalysis( inputs: TerrainAnalysisInputs, criteria: TerrainCriteria, color: UIColor ) -> FieldAnalysis { // Create Boolean masks that select cells within the inclusive // slope and elevation ranges. The long-form comparison methods // can be used instead of these operator overloads. let slopeRangeMask = (inputs.slopeFunction .>= criteria.slopeRange.lowerBound) .& (inputs.slopeFunction .<= criteria.slopeRange.upperBound) let elevationRangeMask = (inputs.elevationFunction .>= criteria.elevationRange.lowerBound) .& (inputs.elevationFunction .<= criteria.elevationRange.upperBound)
let aspectRangeMask = makeAspectRangeMask( aspectFunction: inputs.aspectFunction, start: criteria.aspectStart, end: criteria.aspectEnd )
// Intersect the masks so a cell is suitable only when it meets // every criterion. Remove cells below sea level, then convert the // Boolean result to discrete values for rendering. let scenarioFunction = slopeRangeMask .logicalAnd(with: aspectRangeMask) .logicalAnd(with: elevationRangeMask) .mask(selection: inputs.aboveSeaLevelSelection) .toDiscreteFieldFunction()
// Render false cells in white and suitable cells in the scenario's // color. The analysis starts hidden because // updateAnalysisVisibility() controls which scenario is displayed. let analysis = FieldAnalysis( function: scenarioFunction, renderer: ColormapRenderer(colors: [.white, color]) ) analysis.isVisible = false return analysis }
/// Creates a Boolean mask that selects cells within an aspect range. /// - Parameters: /// - aspectFunction: A function that calculates aspect values in /// degrees clockwise from north. /// - start: The clockwise starting angle of the aspect range. /// - end: The clockwise ending angle of the aspect range. /// - Returns: A Boolean function that selects cells within the aspect /// range. private func makeAspectRangeMask( aspectFunction: ContinuousFieldFunction, start: Float, end: Float ) -> BooleanFieldFunction { if start <= end { (aspectFunction .>= start) .& (aspectFunction .<= end) } else { // A range whose start is greater than its end crosses north, // so join the selections on either side of 0 degrees. ((aspectFunction .>= start) .& (aspectFunction .< 360)) .| ((aspectFunction .>= 0) .& (aspectFunction .<= end)) } } }
/// A predefined combination of slope, aspect, and elevation criteria. enum SiteScenario: CaseIterable, Identifiable { /// Gentle south-facing slopes at low elevations. case gentleSouthFacingSlopes /// Steep west- through north-facing slopes at high elevations. case steepWestAndNorthFacingSlopes
/// The scenario's stable identity. var id: Self { self } /// A concise label describing the scenario. var label: String { switch self { case .gentleSouthFacingSlopes: "Gentle, lowland south-facing slopes" case .steepWestAndNorthFacingSlopes: "Steep, upland west- through north-facing slopes" } } /// A description of the terrain found by the scenario. var description: String { switch self { case .gentleSouthFacingSlopes: """ Finds sheltered, lowland terrain with gentle south-facing \ slopes. """ case .steepWestAndNorthFacingSlopes: """ Finds exposed, upland terrain with steep west- through \ north-facing slopes. """ } } }}
/// The field functions used to evaluate terrain suitability.private struct TerrainAnalysisInputs { /// A function that calculates slope from the elevation field. let slopeFunction: ContinuousFieldFunction /// A function that calculates aspect from the elevation field. let aspectFunction: ContinuousFieldFunction /// A function that supplies elevation values. let elevationFunction: ContinuousFieldFunction /// A Boolean function that selects cells at or above sea level. let aboveSeaLevelSelection: BooleanFieldFunction}
/// The value ranges that define suitable terrain for a scenario.private struct TerrainCriteria { /// The inclusive range of suitable slope angles, in degrees. let slopeRange: ClosedRange<Float> /// The clockwise starting angle of the suitable aspect range, in degrees /// from north. let aspectStart: Float /// The clockwise ending angle of the suitable aspect range, in degrees /// from north. let aspectEnd: Float /// The inclusive range of suitable elevations, in meters. let elevationRange: ClosedRange<Float>
/// The criteria for gentle, lowland south-facing slopes. static let gentleSouthFacingSlopes = TerrainCriteria( slopeRange: 0...20, aspectStart: 112.5, aspectEnd: 247.5, elevationRange: 0...300 ) /// The criteria for steep, upland west- through north-facing slopes. static let steepWestAndNorthFacingSlopes = TerrainCriteria( slopeRange: 20...80, aspectStart: 247.5, aspectEnd: 67.5, elevationRange: 300...850 )}
private extension URL { /// A URL to the local GeoTIFF elevation raster of the Isle of Arran, /// Scotland. static func terrainSuitabilityArranElevation() throws -> URL { guard let url = Bundle.main.url( forResource: "arran", withExtension: "tif", subdirectory: "arran" ) else { throw URLError(.fileDoesNotExist) } return url }}