Skip to content

Show service area

View on GitHubSample viewer app

Find the service area within a network from a given point.

Image of show service area

Use case

A service area shows locations that can be reached from a facility based on a certain impedance, such as travel time or distance. Barriers can increase impedance by either adding to the time it takes to pass through the barrier or by altogether preventing passage.

For example, you might calculate the region around a hospital in which ambulances can service in 30 minutes or less.

How to use the sample

  • To add a facility, select the "Facilities" mode and tap anywhere on the map.
  • To add a barrier, select the "Barriers" mode and tap on the map to add barrier polygons.
  • Use the "Set time breaks" button to adjust the time break values for the service area calculation.
  • Tap the "Solve Service Area" button to calculate and display the service area polygons around the facilities, considering any barriers.
  • Use the "Clear" button to remove all facilities, barriers, and service area polygons from the map.

How it works

  1. Create a ServiceAreaTask from a network analysis service.
  2. Create default ServiceAreaParameters from the service area task.
  3. Set the parameters to return polygons and dissolve overlapping areas.
  4. Add one or more ServiceAreaFacility instances at the locations of the facility graphics.
  5. Add any polygon barriers as PolygonBarrier instances.
  6. Set the time breaks (impedance cutoffs) for the service area calculation.
  7. Solve the service area task using the parameters to get a ServiceAreaResult.
  8. Get any ServiceAreaPolygon results and display them as graphics in a GraphicsOverlay on the map.

Relevant API

  • PolygonBarrier
  • ServiceAreaFacility
  • ServiceAreaParameters
  • ServiceAreaPolygon
  • ServiceAreaResult
  • ServiceAreaTask

Tags

barriers, facilities, impedance, logistics, network analysis, routing, service area

Sample Code

ShowServiceAreaViewModel.ktShowServiceAreaViewModel.ktMainActivity.ktShowServiceAreaScreen.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
/* 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.showservicearea.components

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.arcgismaps.Color
import com.arcgismaps.geometry.GeometryEngine
import com.arcgismaps.geometry.Point
import com.arcgismaps.geometry.Polygon
import com.arcgismaps.geometry.SpatialReference
import com.arcgismaps.mapping.ArcGISMap
import com.arcgismaps.mapping.BasemapStyle
import com.arcgismaps.mapping.Viewpoint
import com.arcgismaps.mapping.symbology.PictureMarkerSymbol
import com.arcgismaps.mapping.symbology.SimpleFillSymbol
import com.arcgismaps.mapping.symbology.SimpleFillSymbolStyle
import com.arcgismaps.mapping.symbology.SimpleLineSymbol
import com.arcgismaps.mapping.symbology.SimpleLineSymbolStyle
import com.arcgismaps.mapping.symbology.SimpleRenderer
import com.arcgismaps.mapping.symbology.Symbol
import com.arcgismaps.mapping.view.Graphic
import com.arcgismaps.mapping.view.GraphicsOverlay
import com.arcgismaps.tasks.networkanalysis.PolygonBarrier
import com.arcgismaps.tasks.networkanalysis.ServiceAreaFacility
import com.arcgismaps.tasks.networkanalysis.ServiceAreaOverlapGeometry
import com.arcgismaps.tasks.networkanalysis.ServiceAreaPolygon
import com.arcgismaps.tasks.networkanalysis.ServiceAreaTask
import com.arcgismaps.toolkit.geoviewcompose.MapViewProxy
import com.esri.arcgismaps.sample.sampleslib.components.MessageDialogViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

/**
 * ViewModel for the Show Service Area sample.
 * Handles all ArcGIS Maps SDK logic, state, and exposes flows for Compose UI.
 */
class ShowServiceAreaViewModel(app: Application) : AndroidViewModel(app) {
    // ArcGISMap centered over San Diego
    val arcGISMap = ArcGISMap(BasemapStyle.ArcGISTerrain).apply {
        initialViewpoint = Viewpoint(
            center = Point(
                x = -13041154.0,
                y = 3858170.0,
                spatialReference = SpatialReference.webMercator()
            ),
            scale = 60000.0
        )
    }

    // MapViewProxy for identify operations and map interaction
    val mapViewProxy = MapViewProxy()

    // Graphics overlays for facilities, barriers, and service areas
    private val facilitiesOverlay = GraphicsOverlay().apply {
        renderer = SimpleRenderer(
            symbol = PictureMarkerSymbol( // Use a blue star pin for facilities
                url = "https://static.arcgis.com/images/Symbols/Shapes/BluePin1LargeB.png"
            ).apply {
                // Offset to align image properly
                offsetY = 21f
            })
    }
    private val barriersOverlay = GraphicsOverlay().apply {
        // Red diagonal cross fill for barriers
        val barrierSymbol = SimpleFillSymbol(
            style = SimpleFillSymbolStyle.DiagonalCross,
            color = Color.red,
            outline = null
        )
        renderer = SimpleRenderer(barrierSymbol)
    }
    private val serviceAreaOverlay = GraphicsOverlay()

    // Expose overlays as a list for MapView
    val graphicsOverlays = listOf(facilitiesOverlay, barriersOverlay, serviceAreaOverlay)

    // Service area task for the San Diego network analysis service
    private val serviceAreaTask = ServiceAreaTask(
        url = "https://sampleserver7.arcgisonline.com/server/rest/services/NetworkAnalysis/SanDiego/NAServer/ServiceArea"
    )

    // StateFlow for the currently selected graphic type (facility or barrier)
    private val _selectedGraphicType = MutableStateFlow(GraphicType.Facility)
    val selectedGraphicType: StateFlow<GraphicType> = _selectedGraphicType.asStateFlow()

    // StateFlow for time break values (combined in a data class)
    private val _timeBreaks = MutableStateFlow(TimeBreaks(3, 8))
    val timeBreaks: StateFlow<TimeBreaks> = _timeBreaks.asStateFlow()

    // StateFlow for loading status (used to show loading dialog)
    private val _isSolvingServiceArea = MutableStateFlow(false)
    val isSolvingServiceArea: StateFlow<Boolean> = _isSolvingServiceArea.asStateFlow()

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

    /**
     * Called when the user taps the map to add a facility or barrier
     * at the given [mapPoint] coordinates.
     */
    fun onSingleTap(mapPoint: Point) {
        when (_selectedGraphicType.value) {
            GraphicType.Facility -> addFacilityGraphic(mapPoint)
            GraphicType.Barrier -> addBarrierGraphic(mapPoint)
        }
    }

    /**
     * Adds a facility graphic to the facilities overlay at the given [point].
     */
    private fun addFacilityGraphic(point: Point) {
        val graphic = Graphic(geometry = point)
        facilitiesOverlay.graphics.add(graphic)
    }

    /**
     * Adds a barrier graphic (buffered polygon) to the barriers overlay at the given [point].
     */
    private fun addBarrierGraphic(point: Point) {
        val bufferedGeometry = GeometryEngine.bufferOrNull(geometry = point, distance = 500.0)
        val graphic = Graphic(geometry = bufferedGeometry)
        barriersOverlay.graphics.add(graphic)
    }

    /**
     * Removes all graphics from all overlays (reset the sample).
     */
    fun removeAllGraphics() {
        facilitiesOverlay.graphics.clear()
        barriersOverlay.graphics.clear()
        serviceAreaOverlay.graphics.clear()
    }

    /**
     * Update the selected graphic type (facility or barrier) for adding graphics.
     */
    fun updateSelectedGraphicType(type: GraphicType) {
        _selectedGraphicType.value = type
    }

    /**
     * Updates the time break values for service area calculation.
     */
    fun updateTimeBreaks(first: Int, second: Int) {
        _timeBreaks.value = TimeBreaks(first, second)
        showServiceArea()
    }

    /**
     * Calculates and displays the service area polygons for the current facilities and barriers.
     * Uses the time breaks specified by the user.
     */
    fun showServiceArea() {
        // Only allow one solve at a time
        if (_isSolvingServiceArea.value) return
        _isSolvingServiceArea.value = true
        viewModelScope.launch {
            try {
                // Always create new parameters for each solve
                val serviceAreaParameters = serviceAreaTask.createDefaultParameters().getOrElse {
                    return@launch messageDialogVM.showMessageDialog(it)
                }
                serviceAreaParameters.geometryAtOverlap = ServiceAreaOverlapGeometry.Dissolve
                // Clear previous service area graphics
                serviceAreaOverlay.graphics.clear()
                // Set facilities from facility graphics
                val facilities = facilitiesOverlay.graphics.mapNotNull { graphic ->
                    (graphic.geometry as? Point)?.let { ServiceAreaFacility(it) }
                }
                serviceAreaParameters.setFacilities(facilities)
                // Set polygon barriers from barrier graphics
                val barriers = barriersOverlay.graphics.mapNotNull { graphic ->
                    (graphic.geometry as? Polygon)?.let { PolygonBarrier(it) }
                }
                serviceAreaParameters.setPolygonBarriers(barriers)
                // Set the time breaks (impedance cutoffs)
                serviceAreaParameters.defaultImpedanceCutoffs.clear()
                serviceAreaParameters.defaultImpedanceCutoffs.addAll(
                    listOf(_timeBreaks.value.first.toDouble(), _timeBreaks.value.second.toDouble())
                )
                // Solve the service area
                val result = serviceAreaTask.solveServiceArea(serviceAreaParameters)
                    .getOrElse { return@launch messageDialogVM.showMessageDialog(it) }
                // Display polygons for the first facility (if any)
                val polygons: List<ServiceAreaPolygon> = result.getResultPolygons(0)
                polygons.forEachIndexed { index, polygon ->
                    val fillSymbol = createServiceAreaSymbol(index == 0)
                    val graphic = Graphic(
                        geometry = polygon.geometry,
                        symbol = fillSymbol
                    )
                    serviceAreaOverlay.graphics.add(graphic)
                }
            } finally {
                _isSolvingServiceArea.value = false
            }
        }
    }

    /**
     * Creates a fill symbol for the service area polygons.
     * If [isFirst] use, polygon (yellow) else, second (green).
     */
    private fun createServiceAreaSymbol(isFirst: Boolean): Symbol {
        // Colors are semi-transparent
        val lineSymbolColor = if (isFirst) {
            Color.fromRgba(r = 100, g = 100, b = 0, a = 70) // Yellow outline
        } else {
            Color.fromRgba(r = 0, g = 100, b = 0, a = 70) // Green outline
        }
        val fillSymbolColor = if (isFirst) {
            Color.fromRgba(r = 200, g = 200, b = 0, a = 70) // Yellow fill
        } else {
            Color.fromRgba(r = 0, g = 200, b = 0, a = 70) // Green fill
        }

        val outline = SimpleLineSymbol(
            style = SimpleLineSymbolStyle.Solid,
            color = lineSymbolColor,
            width = 2f
        )
        return SimpleFillSymbol(
            style = SimpleFillSymbolStyle.Solid,
            color = fillSymbolColor,
            outline = outline
        )
    }

    /**
     * Enum for the type of graphic to add (facility or barrier).
     */
    enum class GraphicType(val label: String) {
        Facility("Facilities"),
        Barrier("Barriers")
    }

    /**
     * Data class for holding both time break values together.
     */
    data class TimeBreaks(val first: Int, val second: Int)
}

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