Skip to content
View on GitHub

Perform a line of sight analysis in a map view between fixed observer and target positions.

Show line of sight analysis in map sample

Use case

Line of sight analysis determines whether a target can be seen from one or more observer locations based on elevation data. This can support planning workflows such as siting communication equipment, assessing observation coverage, or evaluating potential obstructions between known locations. In this sample, several predefined observer points are evaluated against a single fixed target to compare visibility outcomes side by side.

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 map centered on the Isle of Arran, Scotland, and runs a line of sight analysis from multiple observer points (triangles) to a fixed target point (beacon icon) located at the highest point of the island. Solid green line segments represent visible portions of each line of sight result, and dashed gray segments represent not visible portions. Tap on each observer to see a callout that reports whether the target is visible and over what distance the line remains unobstructed. Use the toggle to show only results where the target is visible from the observer.

How it works

  1. Create a Map and pass it to a MapView.
  2. Create a GraphicsOverlay and add target and observer points to it, along with an appropriate symbol. Create another GraphicsOverlay that will display the line of sight result graphics.
  3. Create a ContinuousField from a raster file containing elevation data.
  4. Create a list of LineOfSightPosition from target and observer Points and a HeightOrigin.relative.
  5. Configure LineOfSightParameters with ObserverTargetPairs, using the list of observer and target line of sight positions.
  6. Create a LineOfSightFunction from the continuous field and line of sight parameters.
  7. Evaluate the function to get LineOfSight results.
  8. Create a Graphic from each result, using the geometry of the result's visibleLine or notVisibleLine result, and an appropriate symbol.
  9. Use LineOfSight.targetVisibility to determine if the observer position has a direct line of sight to the target position.
  10. Get the length of the visible line result with GeometryEngine.geodeticLength(of:lengthUnit:curveType:) to report results.

Relevant API

  • ContinuousField
  • GeometryEngine
  • GraphicsOverlay
  • LineOfSight
  • LineOfSightFunction
  • LineOfSightParameters
  • LineOfSightPosition
  • ObserverTargetPairs

About the data

The sample uses a 10m resolution digital terrain elevation raster of the Isle of Arran, Scotland (Raster data Copyright Scottish Government and SEPA (2014)).

Tags

analysis, elevation, line of sight, map view, spatial analysis, terrain, visibility

Sample Code

ShowLineOfSightAnalysisInMapView.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
282
// 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 ShowLineOfSightAnalysisInMapView: View {
    /// The view model for the sample.
    @State private var model = Model()
    /// The placement of the visibility description callout.
    @State private var calloutPlacement: CalloutPlacement?
    /// A Boolean value indicating whether the obstructed line of sight graphics are showing.
    @State private var isShowingObstructed = true
    /// The error shown in the error alert.
    @State private var error: (any Error)?

    /// The states of the sample.
    private enum SampleState: Equatable {
        /// A line of sight analysis is being run.
        case evaluatingLinesOfSight
        /// The given tap point is being identified.
        case identifying(tapPoint: CGPoint)
    }

    /// The current state of the sample.
    @State private var sampleState: SampleState? = .evaluatingLinesOfSight

    var body: some View {
        MapViewReader { mapViewProxy in
            MapView(map: model.map, graphicsOverlays: model.graphicOverlays)
                .callout(placement: $calloutPlacement.animation(.default.speed(2))) { placement in
                    if let attributes = placement.geoElement?.attributes,
                       let visibilityDescription = attributes[.visibilityDescription] as? String {
                        Text(visibilityDescription)
                            .padding(6)
                    }
                }
                .onSingleTapGesture { screenPoint, _ in
                    guard sampleState == nil else { return }
                    sampleState = .identifying(tapPoint: screenPoint)
                }
                .task(id: sampleState) {
                    guard let sampleState else { return }
                    defer { self.sampleState = nil }

                    do {
                        switch sampleState {
                        case .evaluatingLinesOfSight:
                            try await model.evaluateLinesOfSight()
                        case let .identifying(tapPoint):
                            calloutPlacement = nil

                            let identifyResult = try await mapViewProxy.identify(
                                on: model.observerGraphicsOverlay,
                                screenPoint: tapPoint,
                                tolerance: 10
                            )

                            guard let observerGraphic = identifyResult.graphics.first else { return }
                            calloutPlacement = .geoElement(observerGraphic)
                        }
                    } catch {
                        self.error = error
                    }
                }
                .errorAlert(presentingError: $error)
        }
        .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) {
                Menu("Settings", systemImage: "gear") {
                    Toggle("Show Obstructed", isOn: $isShowingObstructed)
                        .onChange(of: isShowingObstructed) {
                            model.setObstructedVisibility(isVisible: isShowingObstructed)
                        }
                }
            }
        }
    }
}

// MARK: Model

/// The view model for this sample.
@Observable
private final class Model {
    /// A map with a dark hillshade basemap initially centered on the Isle of Arran, Scotland.
    let map: Map = {
        let map = Map(basemapStyle: .arcGISHillshadeDark)
        let initialExtent = Envelope(xRange: -585030 ... -570890, yRange: 7472900 ... 7495670)
        map.initialViewpoint = Viewpoint(boundingGeometry: initialExtent)
        return map
    }()

    /// The overlays containing the graphics to display on the map.
    var graphicOverlays: [GraphicsOverlay] {
        return [lineOfSightGraphicsOverlay, targetGraphicsOverlay, observerGraphicsOverlay]
    }

    /// The overlay containing the observer position graphics.
    let observerGraphicsOverlay = GraphicsOverlay()

    /// The overlay containing the target position graphic.
    private let targetGraphicsOverlay = GraphicsOverlay()

    /// The overlay containing the line of sight analysis result graphics.
    private let lineOfSightGraphicsOverlay = GraphicsOverlay()

    /// The height of the target and observer position points.
    private static let positionHeight = 5.0

    /// The target observer's location on the map.
    private let targetPoint = Point(
        x: -577955.365,
        y: 7484288.220,
        z: positionHeight,
        spatialReference: .webMercator
    )

    /// An observer of a line of sight analysis.
    private struct Observer {
        /// The observer's location on the map in Web Mercator.
        let point: Point
        /// The observer's symbol for its graphic.
        let symbol: SimpleMarkerSymbol

        init(x: Double, y: Double, color: UIColor) {
            point = Point(x: x, y: y, z: positionHeight, spatialReference: .webMercator)
            symbol = SimpleMarkerSymbol(style: .triangle, color: color, size: 15)
        }
    }

    /// The observers to evaluate lines of sight for.
    private let observers = [
        Observer(x: -580893.546, y: 7489102.890, color: .green),
        Observer(x: -583446.004, y: 7483567.462, color: .white),
        Observer(x: -577665.236, y: 7490792.908, color: .orange),
        Observer(x: -576452.981, y: 7487071.388, color: .yellow),
        Observer(x: -576650.067, y: 7481479.772, color: .purple),
        Observer(x: -571683.896, y: 7492017.864, color: .blue)
    ]

    init() {
        // Creates graphics to display the target and observer positions on the map.
        let beaconSymbol = PictureMarkerSymbol(image: .beacon)
        beaconSymbol.width = 22
        beaconSymbol.height = 22

        let targetGraphic = Graphic(geometry: targetPoint, symbol: beaconSymbol)
        targetGraphicsOverlay.addGraphic(targetGraphic)

        let observerGraphics = observers.map { Graphic(geometry: $0.point, symbol: $0.symbol) }
        observerGraphicsOverlay.addGraphics(observerGraphics)
    }

    /// Runs a line of sight analysis.
    @MainActor
    func evaluateLinesOfSight() async throws {
        // Creates a continuous field using a TIF file containing elevation data.
        let elevationField = try await ContinuousField.field(fromFilesAt: [.arranTIF], bandIndex: 0)

        // Creates line of sight parameters with target and observer positions.
        let parameters = LineOfSightParameters()
        let targetPosition = LineOfSightPosition(position: targetPoint, heightOrigin: .relative)
        let observerPositions = observers.map { observer in
            LineOfSightPosition(position: observer.point, heightOrigin: .relative)
        }
        parameters.observerTargetPairs = ObserverTargetPairs(
            observers: observerPositions,
            targets: [targetPosition],
        )

        // Creates and evaluates a line of sight function to get the lines of sight.
        let lineOfSightFunction = LineOfSightFunction(
            elevation: elevationField,
            parameters: parameters,
        )
        let lineOfSightResults = try await lineOfSightFunction.evaluate()

        // Creates and adds graphics for the results to show the lines of sight on the map.
        let lineOfSightGraphics = makeLineOfSightGraphics(lineOfSightResults)
        lineOfSightGraphicsOverlay.addGraphics(lineOfSightGraphics)

        // Adds descriptions of the results' visibility to the corresponding observer graphics.
        let lineOfSightObserverPairs = zip(lineOfSightResults, observerGraphicsOverlay.graphics)
        for (lineOfSight, observerGraphic) in lineOfSightObserverPairs {
            let visibilityDescription = lineOfSight.visibilityDescription
            observerGraphic.setAttributeValue(visibilityDescription, forKey: .visibilityDescription)
        }
    }

    /// Sets the visibility of the obstructed line of sight graphics.
    /// - Parameter isVisible: A Boolean value indicating whether the graphics should be visible.
    func setObstructedVisibility(isVisible: Bool) {
        for graphic in lineOfSightGraphicsOverlay.graphics {
            guard let targetVisibility = graphic.attributes[.targetVisibility] as? Float,
                  targetVisibility != 1 else {
                continue
            }
            graphic.isVisible = isVisible
        }
    }

    /// Creates graphics for displaying line of sight visibilities.
    /// - Parameter linesOfSight: The lines of sight results to create graphics for.
    private func makeLineOfSightGraphics(_ linesOfSight: [LineOfSight]) -> [Graphic] {
        let visibleLineSymbol = SimpleLineSymbol(color: .green, width: 2)
        let notVisibleLineSymbol = SimpleLineSymbol(style: .longDash, color: .gray)
        return linesOfSight.flatMap { linesOfSight in
            let visibleLineGraphic = Graphic(
                geometry: linesOfSight.visibleLine,
                attributes: [.targetVisibility: linesOfSight.targetVisibility],
                symbol: visibleLineSymbol
            )
            let notVisibleLineGraphic = Graphic(
                geometry: linesOfSight.notVisibleLine,
                attributes: [.targetVisibility: linesOfSight.targetVisibility],
                symbol: notVisibleLineSymbol
            )
            return [visibleLineGraphic, notVisibleLineGraphic]
        }
    }
}

// MARK: Extensions

private extension LineOfSight {
    /// A description of the line of sight's visibility.
    var visibilityDescription: String {
        if let error {
            // Uses the error as the description if line of sight could not be evaluated.
            let illegalStateError = error as? IllegalStateError
            return illegalStateError?.details ?? error.localizedDescription
        } else {
            // Calculates the visible distance from the observer in meters.
            let visibleMeters = if let visibleLine {
                GeometryEngine.geodeticLength(of: visibleLine, lengthUnit: .meters, curveType: .geodesic)
            } else {
                0.0
            }
            let visibleMeasurement = Measurement(value: visibleMeters, unit: UnitLength.meters)

            // Uses `notVisibleLine` to determine if the target is visible from the observer.
            return if notVisibleLine == nil {
                "Target visible from observer after \(visibleMeasurement.formatted())."
            } else {
                "Target obstructed from observer after \(visibleMeasurement.formatted())."
            }
        }
    }
}

private extension String {
    /// A key for an attribute that describes a line of sight's visibility.
    static var visibilityDescription: String { "visibilityDescription" }
    /// A key for an attribute that contains a line of sight's target visibility.
    static var targetVisibility: String { "targetVisibility" }
}

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.