Skip to content
View on GitHub

Perform an interactive viewshed analysis to determine visible and non-visible areas from a given observer position.

Show interactive viewshed with analysis overlay sample

Use case

A viewshed analysis calculates the visible and non-visible areas from an observer's location, based on factors such as elevation and topographic features. For example, an interactive viewshed analysis can be used to identify which areas can be seen from a helicopter moving along a given flight path for monitoring wildfires while taking parameters such as height, field of view, and heading into account to give immediate visual feedback. A user could further extend their viewshed analysis calculations by using map algebra to, e.g., only return viewshed results in geographical areas not covered in forest if they have an additional land cover raster dataset.

Note: This analysis is a form of "data-driven analysis", which means the analysis is calculated at the resolution of the data rather than the resolution of the display.

How to use the sample

The sample loads with a viewshed analysis initialized from an elevation raster covering the Isle of Arran, Scotland. Transparent green shows the area visible from the observer position, and grey shows the non-visible areas. Move the observer position by tapping and dragging over the island to interactively evaluate the viewshed result and display it in the analysis overlay. Alternatively, tap on the map to see the viewshed from the tap location. Tap "Viewshed Settings" and use the controls to explore how the viewshed analysis results change when adjusting the observer elevation, target height, maximum radius, field of view, heading, and elevation sampling interval. As you move the observer and update the viewshed parameters, the analysis overlay refreshes to show the evaluated viewshed result.

How it works

  1. Create a Map and pass it to a MapView.
  2. Create a GraphicsOverlay to draw the observer point and an AnalysisOverlay and pass them to the map view.
  3. Create a ContinuousField from a raster file containing elevation data.
  4. Create and configure ViewshedParameters, passing in a Point as the observer position for the viewshed.
  5. Create a ContinuousFieldFunction from the continuous field.
  6. Create a ViewshedFunction using the continuous field function and viewshed parameters, then convert it to a DiscreteFieldFunction.
  7. Create a ColormapRenderer from a Colormap with colors that represent visible and non-visible results.
  8. Create a FieldAnalysis from the discrete field function and colormap renderer, then add it to the AnalysisOverlay's collection of analysis objects to display the results. As parameter values change, the result is recalculated and redrawn automatically.

Relevant API

  • AnalysisOverlay
  • Colormap
  • ColormapRenderer
  • ContinuousField
  • ContinuousFieldFunction
  • FieldAnalysis
  • ViewshedFunction
  • ViewshedParameters

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

analysis overlay, elevation, field analysis, interactive, raster, spatial analysis, terrain, viewshed, visibility

Sample Code

ShowInteractiveViewshedWithAnalysisOverlayView.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
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
// 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 ArcGIS
import SwiftUI

struct ShowInteractiveViewshedWithAnalysisOverlayView: View {
    /// The view model for the sample.
    @State private var model = Model()
    /// A Boolean value indicating whether the viewshed settings are showing.
    @State private var isShowingSettings = false
    /// The screen point of the viewshed's observer used to determine if it is being dragged.
    @State private var observerScreenPoint: CGPoint?
    /// The error shown in the error alert.
    @State private var error: (any Error)?

    var body: some View {
        MapViewReader { mapViewProxy in
            MapView(
                map: model.map,
                graphicsOverlays: [model.graphicsOverlay],
                analysisOverlays: [model.analysisOverlay]
            )
            .magnifierDisabled(true)
            .onDragGesture { screenPoint, _ in
                guard let observerScreenPoint else { return false }
                return observerScreenPoint.distance(from: screenPoint) < 40
            } onChanged: { screenPoint, mapPoint in
                guard let mapPoint else { return }
                moveObserver(to: mapPoint, screenPoint: screenPoint)
            }
            .onSingleTapGesture { screenPoint, mapPoint in
                moveObserver(to: mapPoint, screenPoint: screenPoint)
            }
            .onDrawStatusChanged { drawStatus in
                // Sets the initial observerScreenPoint value, so the observer can be dragged.
                guard observerScreenPoint == nil,
                      let observerPoint = model.viewshedParameters.observerPosition,
                      drawStatus == .completed else {
                    return
                }
                observerScreenPoint = mapViewProxy.screenPoint(fromLocation: observerPoint)
            }
        }
        .overlay(alignment: .top) {
            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("Viewshed Settings") {
                    isShowingSettings.toggle()
                }
                .popover(isPresented: $isShowingSettings) {
                    ViewshedSettings(parameters: model.viewshedParameters)
                        .presentationCompactAdaptation(.popover)
                        .frame(idealWidth: 320, idealHeight: 380)
                }
            }
        }
        .task {
            do {
                try await model.setUp()
            } catch {
                self.error = error
            }
        }
        .errorAlert(presentingError: $error)
    }

    /// Moves the observer using given points.
    /// - Parameters:
    ///   - mapPoint: The map point to move the observer to.
    ///   - screenPoint: The screen point corresponding to the map point.
    private func moveObserver(to mapPoint: Point, screenPoint: CGPoint) {
        let elevatedMapPoint = mapPoint.withBuilder { point in
            point.z = model.viewshedParameters.observerPosition?.z ?? 0
        }
        model.viewshedParameters.observerPosition = elevatedMapPoint
        model.observerGraphic.geometry = elevatedMapPoint

        observerScreenPoint = screenPoint
    }
}

// MARK: Model

/// The view model for this sample.
@MainActor
@Observable
private final class Model {
    /// A analysis overlay for displaying the viewshed analysis.
    let analysisOverlay = AnalysisOverlay()

    /// A graphics overlay for displaying the observer graphic.
    let graphicsOverlay = GraphicsOverlay()

    /// A map with a imagery basemap initially centered on the Isle of Arran, Scotland.
    let map: Map = {
        let map = Map(basemapStyle: .arcGISImagery)
        let initialExtent = Envelope(xRange: -583160 ... -575630, yRange: 7476430...7488550)
        map.initialViewpoint = Viewpoint(boundingGeometry: initialExtent)
        return map
    }()

    /// A blue circle graphic used to represent the analysis' observer position.
    let observerGraphic = Graphic(symbol: SimpleMarkerSymbol(color: .blue, size: 10))

    /// The parameters for creating and controlling the viewshed analysis.
    let viewshedParameters: ViewshedParameters = {
        let parameters = ViewshedParameters()
        parameters.fieldOfView = 150
        parameters.heading = 10
        parameters.maxRadius = 8000
        parameters.observerPosition = Point(
            x: -579246,
            y: 7479619,
            z: 20,
            spatialReference: .webMercator
        )
        parameters.targetHeight = 20
        return parameters
    }()

    /// Creates and adds a viewshed analysis to the analysis overlay.
    func setUp() async throws {
        // Creates a discrete field viewshed function using a TIF file and viewshed parameters.
        let elevationField = try await ContinuousField.field(fromFilesAt: [.arranTIF], bandIndex: 0)
        let elevationFunction = ContinuousFieldFunction.function(withResult: elevationField)
        let viewshedFunction = ViewshedFunction(
            elevation: elevationFunction,
            parameters: viewshedParameters
        )
        let discreteViewshed = viewshedFunction.toDiscreteFieldFunction()

        // Creates a colormap renderer to visualize the visible and non-visible results.
        let notVisibleColor: UIColor = .gray.withAlphaComponent(0.7)
        let visibleColor: UIColor = .green.withAlphaComponent(0.3)
        let colormapRenderer = ColormapRenderer(colors: [notVisibleColor, visibleColor])

        // Creates an analysis and adds it to the analysis overlay to display it.
        let viewshedAnalysis = FieldAnalysis(function: discreteViewshed, renderer: colormapRenderer)
        analysisOverlay.addAnalysis(viewshedAnalysis)

        // Sets up a graphic to represent the viewshed analysis' observer.
        observerGraphic.geometry = viewshedParameters.observerPosition
        graphicsOverlay.addGraphic(observerGraphic)
    }
}

// MARK: Helper Views

/// Controls for adjusting a viewshed analysis.
private struct ViewshedSettings: View {
    /// The parameters for controlling the viewshed analysis.
    let parameters: ViewshedParameters

    /// The interval at which the elevation source is sampled.
    @State private var elevationSamplingInterval = 0.0
    /// The field of view of the observer.
    @State private var fieldOfView = Measurement(value: 0, unit: UnitAngle.degrees)
    /// The direction that the observer is facing.
    @State private var heading = Measurement(value: 0, unit: UnitAngle.degrees)
    /// The maximum radius for the viewshed calculation.
    @State private var maxRadius = Measurement(value: 0, unit: UnitLength.meters)
    /// The elevation of the observer position in 3D space.
    @State private var observerElevation = Measurement(value: 0, unit: UnitLength.meters)
    /// The height of the target.
    @State private var targetHeight = Measurement(value: 0, unit: UnitLength.meters)

    var body: some View {
        Form {
            Group {
                VStack {
                    LabeledContent("Observer Elevation", value: observerElevation, format: .length)
                    Slider(value: $observerElevation.value, in: 2...200, step: 1)
                        .onChange(of: observerElevation) {
                            parameters.observerPosition = parameters.observerPosition?.withBuilder {
                                $0.z = observerElevation.value
                            }
                        }
                }
                VStack {
                    LabeledContent("Target Height", value: targetHeight, format: .length)
                    Slider(value: $targetHeight.value, in: 20...1000, step: 10)
                        .onChange(of: targetHeight) {
                            parameters.targetHeight = targetHeight.value
                        }
                }
                VStack {
                    LabeledContent("Max Radius", value: maxRadius, format: .length)
                    Slider(value: $maxRadius.value, in: 2500...20000, step: 100)
                        .onChange(of: maxRadius) {
                            parameters.maxRadius = maxRadius.value
                        }
                }
                VStack {
                    LabeledContent("Field of View", value: fieldOfView, format: .angle)
                    Slider(value: $fieldOfView.value, in: 5...360, step: 1)
                        .onChange(of: fieldOfView) {
                            parameters.fieldOfView = fieldOfView.value
                        }
                }
                VStack {
                    LabeledContent("Heading", value: heading, format: .angle)
                    Slider(value: $heading.value, in: 0...360, step: 1)
                        .onChange(of: heading) {
                            parameters.heading = heading.value
                        }
                }
                VStack {
                    Text("Elevation Sampling Interval (m)")
                    Picker("Elevation Sampling Interval", selection: $elevationSamplingInterval) {
                        Text("0").tag(0.0)
                        Text("10").tag(10.0)
                        Text("20").tag(20.0)
                    }
                    .pickerStyle(.segmented)
                    .onChange(of: elevationSamplingInterval) {
                        parameters.elevationSamplingInterval = elevationSamplingInterval
                    }
                }
            }
#if targetEnvironment(macCatalyst)
            .padding(.vertical)
#endif
        }
        .onAppear {
            // Sets the state property initial values using the parameters.
            elevationSamplingInterval = parameters.elevationSamplingInterval
            fieldOfView.value = parameters.fieldOfView
            heading.value = parameters.heading
            maxRadius.value = parameters.maxRadius ?? 0
            observerElevation.value = parameters.observerPosition?.z ?? 0
            targetHeight.value = parameters.targetHeight
        }
    }
}

// MARK: Extensions

private extension CGPoint {
    /// Returns the Euclidean distance from this point to another point.
    /// - Parameter other: The point to measure the distance from.
    func distance(from other: CGPoint) -> CGFloat {
        let dx = other.x - x
        let dy = other.y - y
        return sqrt(dx * dx + dy * dy)
    }
}

private extension FormatStyle where Self == Measurement<UnitAngle>.FormatStyle {
    /// A style for formatting a unit angle measurement.
    static var angle: Self { .measurement(width: .narrow, usage: .asProvided) }
}

private extension FormatStyle where Self == Measurement<UnitLength>.FormatStyle {
    /// A style for formatting a unit length measurement.
    static var length: Self { .measurement(width: .abbreviated, usage: .asProvided) }
}

private extension URL {
    /// A URL to a local GeoTIFF file containing elevation data of the Isle of Arran, Scotland.
    static var arranTIF: URL {
        Bundle.main.url(forResource: "arran", withExtension: "tif", subdirectory: "arran")!
    }
}

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