Viewshed location

View inJavaKotlin
View on GitHub
Sample viewer app

Perform a viewshed analysis from a defined vantage point.

Image of viewshed location

Use case

A 3D viewshed analysis is a type of visual analysis you can perform on a scene. The viewshed shows what can be seen from a given location. The output is an overlay with two different colors - one representing the visible areas (green) and the other representing the obstructed areas (red). Viewshed analysis is a form of "exploratory analysis", which means the results are calculated on the current scale of the data, and the results are generated very quickly. If more "conclusive" results are required, consider using a GeoprocessingTask to perform a viewshed instead.

How to use the sample

Use the sliders to change the properties (heading, pitch, etc.), of the viewshed and see them updated in real time. To move the viewshed, double touch and drag your finger across the screen. Lift your finger to stop moving the viewshed.

How it works

  1. Create a LocationViewshed passing in the observer location, heading, pitch, horizontal/vertical angles, and min/max distances.
  2. Set the property values on the viewshed instance for location, direction, range, and visibility properties.

Relevant API

  • AnalysisOverlay
  • ArcGISTiledElevationSource
  • ArcGISSceneLayer
  • LocationViewshed
  • Viewshed

About the data

The scene shows a buildings layer in Brest, France hosted on ArcGIS Online.

Tags

3D, frustum, scene, viewshed, visibility analysis

Sample Code

MainActivity.kt
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
/*
 * 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.
 *
 */

package com.esri.arcgisruntime.sample.viewshedlocation

import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.MotionEvent
import android.widget.CheckBox
import android.widget.SeekBar
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.esri.arcgisruntime.ArcGISRuntimeEnvironment
import com.esri.arcgisruntime.geoanalysis.LocationViewshed
import com.esri.arcgisruntime.geoanalysis.Viewshed
import com.esri.arcgisruntime.geometry.Point
import com.esri.arcgisruntime.layers.ArcGISSceneLayer
import com.esri.arcgisruntime.mapping.*
import com.esri.arcgisruntime.mapping.view.*
import com.esri.arcgisruntime.sample.viewshedlocation.databinding.ActivityMainBinding
import java.util.concurrent.ExecutionException
import kotlin.math.roundToInt


class MainActivity : AppCompatActivity() {

    // initialize location viewshed parameters
    private val initHeading = 0
    private val initPitch = 60
    private val initHorizontalAngle = 75
    private val initVerticalAngle = 90
    private val initMinDistance = 0
    private val initMaxDistance = 1500

    private var minDistance: Int = 0
    private var maxDistance: Int = 0

    private lateinit var viewShed: LocationViewshed

    private val activityMainBinding by lazy {
        ActivityMainBinding.inflate(layoutInflater)
    }

    private val sceneView: SceneView by lazy {
        activityMainBinding.sceneView
    }

    private val headingSeekBar: SeekBar by lazy {
        activityMainBinding.include.headingSeekBar
    }

    private val currHeading: TextView by lazy {
        activityMainBinding.include.currHeading
    }

    private val currPitch: TextView by lazy {
        activityMainBinding.include.currPitch
    }

    private val pitchSeekBar: SeekBar by lazy {
        activityMainBinding.include.pitchSeekBar
    }

    private val currHorizontalAngle: TextView by lazy {
        activityMainBinding.include.currHorizontalAngle
    }

    private val horizontalAngleSeekBar: SeekBar by lazy {
        activityMainBinding.include.horizontalAngleSeekBar
    }

    private val currVerticalAngle: TextView by lazy {
        activityMainBinding.include.currVerticalAngle
    }

    private val verticalAngleSeekBar: SeekBar by lazy {
        activityMainBinding.include.verticalAngleSeekBar
    }

    private val currMinimumDistance: TextView by lazy {
        activityMainBinding.include.currMinimumDistance
    }

    private val minDistanceSeekBar: SeekBar by lazy {
        activityMainBinding.include.minDistanceSeekBar
    }

    private val currMaximumDistance: TextView by lazy {
        activityMainBinding.include.currMaximumDistance
    }

    private val maxDistanceSeekBar: SeekBar by lazy {
        activityMainBinding.include.maxDistanceSeekBar
    }

    private val frustumVisibilityCheckBox: CheckBox by lazy {
        activityMainBinding.include.frustumVisibilityCheckBox
    }

    private val viewshedVisibilityCheckBox: CheckBox by lazy {
        activityMainBinding.include.viewshedVisibilityCheckBox
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(activityMainBinding.root)

        // authentication with an API key or named user is required to access basemaps and other
        // location services
        ArcGISRuntimeEnvironment.setApiKey(BuildConfig.API_KEY)

        // create a surface for elevation data
        val surface = Surface().apply {
            elevationSources.add(ArcGISTiledElevationSource(getString(R.string.elevation_service)))
        }

        // create a layer of buildings
        val buildingsSceneLayer = ArcGISSceneLayer(getString(R.string.buildings_layer))

        // create a scene and add imagery basemap, elevation surface, and buildings layer to it
        val buildingsScene = ArcGISScene(BasemapStyle.ARCGIS_IMAGERY).apply {
            baseSurface = surface
            operationalLayers.add(buildingsSceneLayer)
        }

        val initLocation = Point(-4.50, 48.4, 1000.0)

        // create viewshed from the initial location
        viewShed = LocationViewshed(
            initLocation,
            initHeading.toDouble(),
            initPitch.toDouble(),
            initHorizontalAngle.toDouble(),
            initVerticalAngle.toDouble(),
            initMinDistance.toDouble(),
            initMaxDistance.toDouble()
        ).apply {
            setFrustumOutlineVisible(true)
        }

        Viewshed.setFrustumOutlineColor(Color.BLUE)

        sceneView.apply {
            // add the buildings scene to the sceneView
            scene = buildingsScene
            // add a camera and set it to orbit the starting location point of the frustum
            cameraController = OrbitLocationCameraController(initLocation, 5000.0)
            setViewpointCamera(Camera(initLocation, 20000000.0, 0.0, 55.0, 0.0))
        }

        // create an analysis overlay to add the viewshed to the scene view
        val analysisOverlay = AnalysisOverlay().apply {
            analyses.add(viewShed)
        }

        sceneView.analysisOverlays.add(analysisOverlay)

        // initialize the UI controls
        handleUiElements()
    }

    /**
     * Handles double touch drag for movement of viewshed location point and listeners for
     * changes in seek bar progress.
     */
    private fun handleUiElements() {

        sceneView.setOnTouchListener(object : DefaultSceneViewOnTouchListener(sceneView) {

            // double tap and hold second tap to drag viewshed to a new location
            override fun onDoubleTouchDrag(motionEvent: MotionEvent): Boolean {
                // convert from screen point to location point
                val screenPoint = android.graphics.Point(
                    motionEvent.x.roundToInt(),
                    motionEvent.y.roundToInt()
                )
                val locationPointFuture = sceneView.screenToLocationAsync(screenPoint)
                locationPointFuture.addDoneListener {
                    try {
                        val locationPoint = locationPointFuture.get()

                        // add 50 meters to location point and set to viewshed
                        viewShed.location =
                            Point(locationPoint.x, locationPoint.y, locationPoint.z + 50)
                    } catch (e: InterruptedException) {
                        logError("Error converting screen point to location point: " + e.message)
                    } catch (e: ExecutionException) {
                        logError("Error converting screen point to location point: " + e.message)
                    }
                }

                // ignore default double touch drag gesture
                return true
            }
        })

        // toggle visibility of the viewshed
        viewshedVisibilityCheckBox.setOnCheckedChangeListener { buttonView, isChecked ->
            viewShed.isVisible = isChecked
        }

        // toggle visibility of the frustum outline
        frustumVisibilityCheckBox.setOnCheckedChangeListener { buttonView, isChecked ->
            viewShed.setFrustumOutlineVisible(isChecked)
        }

        // heading range 0 - 360
        headingSeekBar.max = 360
        setHeading(initHeading)
        headingSeekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar, i: Int, b: Boolean) {
                setHeading(seekBar.progress)
            }

            override fun onStartTrackingTouch(seekBar: SeekBar) {}

            override fun onStopTrackingTouch(seekBar: SeekBar) {}
        })

        // set arbitrary max to 180 to avoid nonsensical pitch values
        pitchSeekBar.max = 180
        setPitch(initPitch)
        pitchSeekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar, i: Int, b: Boolean) {
                setPitch(seekBar.progress)
            }

            override fun onStartTrackingTouch(seekBar: SeekBar) {}

            override fun onStopTrackingTouch(seekBar: SeekBar) {}
        })

        // horizontal angle range 1 - 120
        horizontalAngleSeekBar.max = 120
        setHorizontalAngle(initHorizontalAngle)
        horizontalAngleSeekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar, i: Int, b: Boolean) {
                val horizontalAngle = horizontalAngleSeekBar.progress
                if (horizontalAngle > 0) { // horizontal angle must be > 0
                    setHorizontalAngle(horizontalAngle)
                }
            }

            override fun onStartTrackingTouch(seekBar: SeekBar) {}

            override fun onStopTrackingTouch(seekBar: SeekBar) {}
        })

        // vertical angle range 1 - 120
        verticalAngleSeekBar.max = 120
        setVerticalAngle(initVerticalAngle)
        verticalAngleSeekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar, i: Int, b: Boolean) {
                val verticalAngle = verticalAngleSeekBar.progress
                if (verticalAngle > 0) { // vertical angle must be > 0
                    setVerticalAngle(verticalAngle)
                }
            }

            override fun onStartTrackingTouch(seekBar: SeekBar) {}

            override fun onStopTrackingTouch(seekBar: SeekBar) {}
        })

        // initialize the minimum distance
        minDistance = initMinDistance

        // set to 1000 below the arbitrary max
        minDistanceSeekBar.max = 8999
        setMinDistance(initMinDistance)
        minDistanceSeekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar, i: Int, b: Boolean) {
                minDistance = seekBar.progress
                if (maxDistance - minDistance < 1000) {
                    maxDistance = minDistance + 1000
                    setMaxDistance(maxDistance)
                }
                setMinDistance(minDistance)
            }

            override fun onStartTrackingTouch(seekBar: SeekBar) {}

            override fun onStopTrackingTouch(seekBar: SeekBar) {}
        })

        // initialize the maximum distance
        maxDistance = initMaxDistance

        // set arbitrary max to 9999 to allow a maximum of 4 digits
        maxDistanceSeekBar.max = 9999
        setMaxDistance(initMaxDistance)
        maxDistanceSeekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar, i: Int, b: Boolean) {
                maxDistance = seekBar.progress
                if (maxDistance - minDistance < 1000) {
                    minDistance = if (maxDistance > 1000) {
                        maxDistance - 1000
                    } else {
                        0
                    }
                    setMinDistance(minDistance)
                }
                setMaxDistance(maxDistance)
            }

            override fun onStartTrackingTouch(seekBar: SeekBar) {}

            override fun onStopTrackingTouch(seekBar: SeekBar) {}
        })
    }

    /**
     * Set viewshed heading, seek bar progress, and current heading text view.
     *
     * @param heading in degrees
     */
    private fun setHeading(heading: Int) {
        headingSeekBar.progress = heading
        currHeading.text = heading.toString()
        viewShed.heading = heading.toDouble()
    }

    /**
     * Set viewshed pitch, seek bar progress, and current pitch text view.
     *
     * @param pitch in degrees
     */
    private fun setPitch(pitch: Int) {
        pitchSeekBar.progress = pitch
        currPitch.text = pitch.toString()
        viewShed.pitch = pitch.toDouble()
    }

    /**
     * Set viewshed horizontal angle, seek bar progress, and current horizontal angle text view.
     *
     * @param horizontalAngle in degrees, > 0 and <= 120
     */
    private fun setHorizontalAngle(horizontalAngle: Int) {
        if (horizontalAngle in 1..120) {
            horizontalAngleSeekBar.progress = horizontalAngle
            currHorizontalAngle.text = horizontalAngle.toString()
            viewShed.horizontalAngle = horizontalAngle.toDouble()
        } else {
            logError("Horizontal angle must be greater than 0 and less than or equal to 120.")
        }
    }

    /**
     * Set viewshed vertical angle, seek bar progress, and current vertical angle text view.
     *
     * @param verticalAngle in degrees, > 0 and <= 120
     */
    private fun setVerticalAngle(verticalAngle: Int) {
        if (verticalAngle in 1..120) {
            verticalAngleSeekBar.progress = verticalAngle
            currVerticalAngle.text = verticalAngle.toString()
            viewShed.verticalAngle = verticalAngle.toDouble()
        } else {
            logError("Vertical angle must be greater than 0 and less than or equal to 120.")
        }
    }

    /**
     * Set viewshed minimum distance, seek bar progress, and current minimum distance text view.
     *
     * @param minDistance in meters
     */
    private fun setMinDistance(minDistance: Int) {
        minDistanceSeekBar.progress = minDistance
        currMinimumDistance.text = minDistance.toString()
        viewShed.minDistance = minDistance.toDouble()
    }

    /**
     * Set viewshed maximum distance, seek bar progress, and current maximum distance text view.
     *
     * @param maxDistance in meters
     */
    private fun setMaxDistance(maxDistance: Int) {
        maxDistanceSeekBar.progress = maxDistance
        currMaximumDistance.text = maxDistance.toString()
        viewShed.maxDistance = maxDistance.toDouble()
    }

    override fun onPause() {
        sceneView.pause()
        super.onPause()
    }

    override fun onResume() {
        super.onResume()
        sceneView.resume()
    }

    override fun onDestroy() {
        sceneView.dispose()
        super.onDestroy()
    }

    /**
     * Log an error to logcat and to the screen via Toast.
     * @param message the text to log.
     */
    private fun logError(message: String?) {
        message?.let {
            Log.e(TAG, message)
            Toast.makeText(this, message, Toast.LENGTH_LONG).show()
        }
    }

    companion object {
        private val TAG: String = MainActivity::class.java.simpleName
    }
}

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