Show viewshed from point on map

View on GitHubSample viewer app

Calculate a viewshed using a geoprocessing service, in this case showing what parts of a landscape are visible from points on mountainous terrain.

Image of show viewshed from point on map

Use case

A viewshed is used to highlight what is visible from a given point. A viewshed could be created to show what a hiker might be able to see from a given point at the top of a mountain. Equally, a viewshed could also be created from a point representing the maximum height of a proposed wind turbine to see from what areas the turbine would be visible.

How to use the sample

Click the map to see all areas visible from that point within a 15km radius. Clicking on an elevated and unobstructed area will highlight a larger part of the surrounding landscape. It may take a few seconds for the task to run and send back the results.

How it works

  1. Create a GeoprocessingTask object with the URL set to a geoprocessing service endpoint.
  2. Create a FeatureCollectionTable object and add a new Feature object whose geometry is the viewshed's observer Point.
  3. Make a GeoprocessingParameters and pass in the GeoprocessingFeatures table which contains the observation point as an input parameter.
  4. Use the geoprocessing task to create a GeoprocessingJob object with the parameters.
  5. Start the job and wait for it to complete and return a GeoprocessingResult object.
  6. Get the resulting GeoprocessingFeatures object.
  7. Iterate through the viewshed GeoprocessingFeatures to use their geometry or display the geometry in a new Graphic object.

Relevant API

  • FeatureCollectionTable
  • GeoprocessingFeatures
  • GeoprocessingJob
  • GeoprocessingParameters
  • GeoprocessingResult
  • GeoprocessingTask

Tags

geoprocessing, heat map, heatmap, viewshed

Sample Code

ShowViewshedFromPointOnMapViewModel.ktShowViewshedFromPointOnMapViewModel.ktMainActivity.ktShowViewshedFromPointOnMapScreen.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
/* Copyright 2025 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.arcgismaps.sample.showviewshedfrompointonmap.components

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.arcgismaps.Color
import com.arcgismaps.data.FeatureCollectionTable
import com.arcgismaps.geometry.GeodeticCurveType
import com.arcgismaps.geometry.GeometryEngine
import com.arcgismaps.geometry.GeometryType
import com.arcgismaps.geometry.LinearUnit
import com.arcgismaps.geometry.Point
import com.arcgismaps.mapping.ArcGISMap
import com.arcgismaps.mapping.BasemapStyle
import com.arcgismaps.mapping.Viewpoint
import com.arcgismaps.mapping.symbology.SimpleFillSymbol
import com.arcgismaps.mapping.symbology.SimpleFillSymbolStyle
import com.arcgismaps.mapping.symbology.SimpleMarkerSymbol
import com.arcgismaps.mapping.symbology.SimpleMarkerSymbolStyle
import com.arcgismaps.mapping.symbology.SimpleRenderer
import com.arcgismaps.mapping.view.Graphic
import com.arcgismaps.mapping.view.GraphicsOverlay
import com.arcgismaps.mapping.view.SingleTapConfirmedEvent
import com.arcgismaps.tasks.geoprocessing.GeoprocessingExecutionType
import com.arcgismaps.tasks.geoprocessing.GeoprocessingJob
import com.arcgismaps.tasks.geoprocessing.GeoprocessingParameters
import com.arcgismaps.tasks.geoprocessing.GeoprocessingTask
import com.arcgismaps.tasks.geoprocessing.geoprocessingparameters.GeoprocessingFeatures
import com.arcgismaps.tasks.geoprocessing.geoprocessingparameters.GeoprocessingLinearUnit
import com.arcgismaps.toolkit.geoviewcompose.MapViewProxy
import com.esri.arcgismaps.sample.sampleslib.components.MessageDialogViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

class ShowViewshedFromPointOnMapViewModel(application: Application) :
    AndroidViewModel(application) {

    // ArcGISMap with a topographic basemap
    val arcGISMap: ArcGISMap = ArcGISMap(BasemapStyle.ArcGISTopographic).apply {
        initialViewpoint = Viewpoint(
            latitude = 45.379,
            longitude = 6.849,
            scale = 144447.0
        )
    }

    // Used by the composable MapView for viewpoint changes
    val mapviewProxy = MapViewProxy()

    // Graphics overlay for the red marker at the tapped location
    val inputGraphicsOverlay = GraphicsOverlay().apply {
        renderer = SimpleRenderer(
            symbol = SimpleMarkerSymbol(
                style = SimpleMarkerSymbolStyle.Circle,
                color = Color.red,
                size = 10f
            )
        )
    }

    // Graphics overlay for displaying the resulting viewshed polygons
    val resultGraphicsOverlay = GraphicsOverlay().apply {
        renderer = SimpleRenderer(
            symbol = SimpleFillSymbol(
                style = SimpleFillSymbolStyle.Solid,
                color = Color.fromRgba(r = 255, g = 165, b = 0, a = 100)
            )
        )
    }

    // Graphics overlay for displaying the 15 km buffer range
    val bufferGraphicsOverlay = GraphicsOverlay().apply {
        renderer = SimpleRenderer(
            symbol = SimpleFillSymbol(
                style = SimpleFillSymbolStyle.Solid,
                color = Color.fromRgba(r = 0, g = 0, b = 255, a = 50)
            )
        )
    }

    // GeoprocessingTask pointing to the Viewshed service URL
    private val geoprocessingTask = GeoprocessingTask(
        url = "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Elevation/ESRI_Elevation_World/GPServer/Viewshed"
    )

    // Running GeoprocessingJob for cancellation/cleanup
    private var geoprocessingJob: GeoprocessingJob? = null

    // State flows for controlling UI
    private val _isGeoprocessingInProgress = MutableStateFlow(false)
    val isGeoprocessingInProgress = _isGeoprocessingInProgress.asStateFlow()

    // Message dialog view model for handling error messages
    val messageDialogVM = MessageDialogViewModel()

    init {
        viewModelScope.launch {
            arcGISMap.load().onFailure { messageDialogVM.showMessageDialog(it) }
        }
    }

    /**
     * Handles the [singleTapConfirmedEvent] by retrieving the tapped [Point] to
     * cancel and run a new viewshed geoprocessing job.
     */
    fun onMapTapped(singleTapConfirmedEvent: SingleTapConfirmedEvent) {
        val tapPoint = singleTapConfirmedEvent.mapPoint
            ?: return messageDialogVM.showMessageDialog("Unable to retrieve tapped point")
        viewModelScope.launch {
            // Clear existing overlays and cancel any running job
            clearOverlays()
            geoprocessingJob?.cancel()
            // Add a new red marker to the map at the tapped point
            addTapMarker(tapPoint)
            // Show a 15 km buffer to visualize the visibility range
            addBufferGraphic(tapPoint)
            // Start the geoprocessing job to obtain the viewshed polygons
            _isGeoprocessingInProgress.value = true
            calculateViewshed(tapPoint)
            _isGeoprocessingInProgress.value = false
        }
    }

    /**
     * Perform the viewshed calculation on the geoprocessing service
     * for the given [tapPoint].
     */
    private suspend fun calculateViewshed(tapPoint: Point) {
        // Create an empty FeatureCollectionTable for the tapped location
        val table = FeatureCollectionTable(
            fields = emptyList(),
            geometryType = GeometryType.Point,
            spatialReference = tapPoint.spatialReference
        )

        // Create a new feature with the tapped geometry and add to the table
        val newFeature = table.createFeature().also { it.geometry = tapPoint }
        table.addFeature(newFeature)

        // Create geoprocessing parameters for a synchronous execution
        val geoprocessingParameters = GeoprocessingParameters(
            geoprocessingExecutionType = GeoprocessingExecutionType.SynchronousExecute
        ).apply {
            processSpatialReference = tapPoint.spatialReference
            outputSpatialReference = tapPoint.spatialReference
            // Provide the tapped point as "Input_Observation_Point"
            inputs["Input_Observation_Point"] = GeoprocessingFeatures(featureSet = table)
            inputs["Viewshed_Distance"] = GeoprocessingLinearUnit(distance = 15000.0)
        }

        // Create a new job
        geoprocessingJob = geoprocessingTask.createJob(geoprocessingParameters)

        // Start and await the result
        geoprocessingJob?.start()

        val gpResult = geoprocessingJob?.result()?.getOrElse {
            return messageDialogVM.showMessageDialog(it)
        }

        // Get the output features for the viewshed polygon
        val viewshedFeatureSet = gpResult?.outputs?.get("Viewshed_Result") as? GeoprocessingFeatures
            ?: return messageDialogVM.showMessageDialog("No viewshed result found in the geoprocessing job.")
        val featureSet = viewshedFeatureSet.features
            ?: return messageDialogVM.showMessageDialog("Geoprocessing feature set is null.")

        // Add each resulting feature geometry as a graphic to resultGraphicsOverlay
        val resultGraphics = featureSet.mapNotNull { feature ->
            feature.geometry?.let { Graphic(it) }
        }

        // Add the graphics to the overlay and set the map's viewpoint to its extent
        resultGraphicsOverlay.graphics.addAll(resultGraphics)
        resultGraphicsOverlay.extent?.let { resultExtent ->
            mapviewProxy.setViewpointGeometry(
                boundingGeometry = resultExtent,
                paddingInDips = 20.0
            )
        }
    }

    /**
     * Place a simple red marker graphic at the tapped location.
     */
    private fun addTapMarker(tapPoint: Point) {
        val graphic = Graphic(tapPoint)
        inputGraphicsOverlay.graphics.add(graphic)
    }

    /**
     * Add a 15 km buffer graphic around [tapPoint].
     */
    private fun addBufferGraphic(tapPoint: Point, radiusMeters: Double = 15000.0) {
        // Use the geometry engine to build a geodesic planar buffer
        val bufferGeometry = GeometryEngine.bufferGeodeticOrNull(
            geometry = tapPoint,
            distance = radiusMeters,
            distanceUnit = LinearUnit.meters,
            maxDeviation = Double.NaN,
            curveType = GeodeticCurveType.Geodesic
        )
        // Create a graphic from the buffered geometry
        val bufferGraphic = Graphic(bufferGeometry)
        // Add it to the buffer graphics overlay
        bufferGraphicsOverlay.graphics.add(bufferGraphic)
    }

    /**
     * Clear any previous marker or result polygons from the map.
     */
    private fun clearOverlays() {
        inputGraphicsOverlay.graphics.clear()
        resultGraphicsOverlay.graphics.clear()
        bufferGraphicsOverlay.graphics.clear()
    }
}

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