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

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
- Create a
ServiceAreaTaskfrom a network analysis service. - Create default
ServiceAreaParametersfrom the service area task. - Set the parameters to return polygons and dissolve overlapping areas.
- Add one or more
ServiceAreaFacilityinstances at the locations of the facility graphics. - Add any polygon barriers as
PolygonBarrierinstances. - Set the time breaks (impedance cutoffs) for the service area calculation.
- Solve the service area task using the parameters to get a
ServiceAreaResult. - Get any
ServiceAreaPolygonresults and display them as graphics in aGraphicsOverlayon the map.
Relevant API
- PolygonBarrier
- ServiceAreaFacility
- ServiceAreaParameters
- ServiceAreaPolygon
- ServiceAreaResult
- ServiceAreaTask
Tags
barriers, facilities, impedance, logistics, network analysis, routing, service area
Sample Code
/* 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
import android.os.Bundleimport androidx.activity.ComponentActivityimport androidx.activity.compose.setContentimport androidx.activity.enableEdgeToEdgeimport androidx.compose.material3.MaterialThemeimport androidx.compose.material3.Surfaceimport androidx.compose.runtime.Composableimport com.arcgismaps.ApiKeyimport com.arcgismaps.ArcGISEnvironmentimport com.esri.arcgismaps.sample.sampleslib.theme.SampleAppThemeimport com.esri.arcgismaps.sample.showservicearea.screens.ShowServiceAreaScreen
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // authentication with an API key or named user is // required to access basemaps and other location services ArcGISEnvironment.apiKey = ApiKey.create(BuildConfig.ACCESS_TOKEN) ArcGISEnvironment.applicationContext = this enableEdgeToEdge() setContent { SampleAppTheme { ShowServiceAreaApp() } } }
@Composable private fun ShowServiceAreaApp() { Surface(color = MaterialTheme.colorScheme.background) { ShowServiceAreaScreen( sampleName = getString(R.string.show_service_area_app_name) ) } }}/* 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.Applicationimport androidx.lifecycle.AndroidViewModelimport androidx.lifecycle.viewModelScopeimport com.arcgismaps.Colorimport com.arcgismaps.geometry.GeometryEngineimport com.arcgismaps.geometry.Pointimport com.arcgismaps.geometry.Polygonimport com.arcgismaps.geometry.SpatialReferenceimport com.arcgismaps.mapping.ArcGISMapimport com.arcgismaps.mapping.BasemapStyleimport com.arcgismaps.mapping.Viewpointimport com.arcgismaps.mapping.symbology.PictureMarkerSymbolimport com.arcgismaps.mapping.symbology.SimpleFillSymbolimport com.arcgismaps.mapping.symbology.SimpleFillSymbolStyleimport com.arcgismaps.mapping.symbology.SimpleLineSymbolimport com.arcgismaps.mapping.symbology.SimpleLineSymbolStyleimport com.arcgismaps.mapping.symbology.SimpleRendererimport com.arcgismaps.mapping.symbology.Symbolimport com.arcgismaps.mapping.view.Graphicimport com.arcgismaps.mapping.view.GraphicsOverlayimport com.arcgismaps.tasks.networkanalysis.PolygonBarrierimport com.arcgismaps.tasks.networkanalysis.ServiceAreaFacilityimport com.arcgismaps.tasks.networkanalysis.ServiceAreaOverlapGeometryimport com.arcgismaps.tasks.networkanalysis.ServiceAreaPolygonimport com.arcgismaps.tasks.networkanalysis.ServiceAreaTaskimport com.arcgismaps.toolkit.geoviewcompose.MapViewProxyimport com.esri.arcgismaps.sample.sampleslib.components.MessageDialogViewModelimport kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.coroutines.flow.StateFlowimport kotlinx.coroutines.flow.asStateFlowimport 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)}/* 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.screens
import android.content.res.Configurationimport androidx.compose.foundation.layout.Arrangementimport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.Rowimport androidx.compose.foundation.layout.Spacerimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.layout.wrapContentHeightimport androidx.compose.foundation.layout.wrapContentSizeimport androidx.compose.material.icons.Iconsimport androidx.compose.material.icons.filled.Deleteimport androidx.compose.material3.Buttonimport androidx.compose.material3.Iconimport androidx.compose.material3.MaterialThemeimport androidx.compose.material3.OutlinedButtonimport androidx.compose.material3.Scaffoldimport androidx.compose.material3.SegmentedButtonimport androidx.compose.material3.SegmentedButtonDefaultsimport androidx.compose.material3.SingleChoiceSegmentedButtonRowimport androidx.compose.material3.Sliderimport androidx.compose.material3.Surfaceimport androidx.compose.material3.Textimport androidx.compose.runtime.Composableimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableIntStateOfimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.setValueimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.tooling.preview.Previewimport androidx.compose.ui.unit.dpimport androidx.lifecycle.compose.collectAsStateWithLifecycleimport androidx.lifecycle.viewmodel.compose.viewModelimport com.arcgismaps.toolkit.geoviewcompose.MapViewimport com.esri.arcgismaps.sample.sampleslib.components.LoadingDialogimport com.esri.arcgismaps.sample.sampleslib.components.MessageDialogimport com.esri.arcgismaps.sample.sampleslib.components.SampleDialogimport com.esri.arcgismaps.sample.sampleslib.components.SamplePreviewSurfaceimport com.esri.arcgismaps.sample.sampleslib.components.SampleTopAppBarimport com.esri.arcgismaps.sample.showservicearea.components.ShowServiceAreaViewModelimport com.esri.arcgismaps.sample.showservicearea.components.ShowServiceAreaViewModel.GraphicTypeimport com.esri.arcgismaps.sample.showservicearea.components.ShowServiceAreaViewModel.TimeBreaks
/** * Main screen layout for the Show Service Area sample app. */@Composablefun ShowServiceAreaScreen(sampleName: String) { val viewModel: ShowServiceAreaViewModel = viewModel()
// Collect state flows from the ViewModel for Compose UI val selectedGraphicType by viewModel.selectedGraphicType.collectAsStateWithLifecycle() val timeBreaks by viewModel.timeBreaks.collectAsStateWithLifecycle() val isSolvingServiceArea by viewModel.isSolvingServiceArea.collectAsStateWithLifecycle()
// Dialog state for showing the time break dialog var showTimeBreakDialog by remember { mutableStateOf(false) }
Scaffold( topBar = { SampleTopAppBar(title = sampleName) }, content = { padding -> Column( modifier = Modifier .fillMaxSize() .padding(padding) ) { // MapView fills most of the screen, responds to taps for adding graphics MapView( modifier = Modifier .fillMaxSize() .weight(1f), arcGISMap = viewModel.arcGISMap, graphicsOverlays = viewModel.graphicsOverlays, mapViewProxy = viewModel.mapViewProxy, onSingleTapConfirmed = { tapEvent -> tapEvent.mapPoint?.let { mapPoint -> // Add facility/barrier depending on selected mode viewModel.onSingleTap(mapPoint) } } ) // Controls area at the bottom ServiceAreaControls( selectedGraphicType = selectedGraphicType, onGraphicTypeSelected = viewModel::updateSelectedGraphicType, timeBreaks = timeBreaks, onShowTimeBreakDialog = { showTimeBreakDialog = true }, onSolveServiceArea = viewModel::showServiceArea, onClearAll = viewModel::removeAllGraphics ) }
// Time breaks dialog if (showTimeBreakDialog) { TimeBreakDialog( initialTimeBreaks = timeBreaks, onApply = { first, second -> viewModel.updateTimeBreaks(first, second) showTimeBreakDialog = false }, onCancel = { showTimeBreakDialog = false } ) }
// Show a loading dialog while the service area is being solved if (isSolvingServiceArea) { LoadingDialog(loadingMessage = "Solving service area...") }
// Show error dialog if needed viewModel.messageDialogVM.apply { if (dialogStatus) { MessageDialog( title = messageTitle, description = messageDescription, onDismissRequest = ::dismissDialog ) } } } )}
/** * Controls for the service area workflow, shown at the bottom of the screen. * Includes: segmented button for mode, row of action buttons. */@Composablefun ServiceAreaControls( selectedGraphicType: GraphicType, onGraphicTypeSelected: (GraphicType) -> Unit, timeBreaks: TimeBreaks, onShowTimeBreakDialog: () -> Unit, onSolveServiceArea: () -> Unit, onClearAll: () -> Unit) { Column( modifier = Modifier .fillMaxWidth() .wrapContentHeight() .padding(vertical = 10.dp, horizontal = 14.dp), verticalArrangement = Arrangement.spacedBy(12.dp), horizontalAlignment = Alignment.CenterHorizontally ) { // Segmented control for Facility/Barrier mode Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center ) { SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) { GraphicType.entries.forEachIndexed { index, type -> SegmentedButton( shape = SegmentedButtonDefaults.itemShape(index, GraphicType.entries.size), onClick = { onGraphicTypeSelected(type) }, selected = selectedGraphicType == type ) { Text(type.label) } } } } // Row of action buttons: Set time breaks, Clear Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly, verticalAlignment = Alignment.CenterVertically ) { OutlinedButton(onClick = onShowTimeBreakDialog) { Text("Set time breaks: ${timeBreaks.first}, ${timeBreaks.second}") } OutlinedButton(onClick = onClearAll) { Icon(Icons.Filled.Delete, contentDescription = "Clear") Text("Clear") } } Button(onClick = onSolveServiceArea) { Text("Solve Service Area") } }}
/** * Dialog for setting time break values with sliders. */@Composablefun TimeBreakDialog( initialTimeBreaks: TimeBreaks, onApply: (first: Int, second: Int) -> Unit, onCancel: () -> Unit) { var firstBreak by remember { mutableIntStateOf(initialTimeBreaks.first) } var secondBreak by remember { mutableIntStateOf(initialTimeBreaks.second) } SampleDialog(onDismissRequest = onCancel) { Column( modifier = Modifier .wrapContentSize() .padding(8.dp), verticalArrangement = Arrangement.spacedBy(18.dp), horizontalAlignment = Alignment.CenterHorizontally ) { Text("Set Time Breaks", style = MaterialTheme.typography.titleMedium) TimeBreakSlider( label = "First time break", value = firstBreak, valueRange = 1..15, onValueChange = { firstBreak = it } ) TimeBreakSlider( label = "Second time break", value = secondBreak, valueRange = 1..15, onValueChange = { secondBreak = it } ) Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End ) { OutlinedButton(onClick = onCancel) { Text("Cancel") } Spacer(Modifier.padding(4.dp)) Button(onClick = { onApply(firstBreak, secondBreak) }) { Text("Apply") } } } }}
/** * Slider row for setting a time break value, with label and value display. */@Composablefun TimeBreakSlider( label: String, value: Int, valueRange: IntRange, onValueChange: (Int) -> Unit) { Column( modifier = Modifier.fillMaxWidth(), verticalArrangement = Arrangement.Center ) { Text("$label: $value min", style = MaterialTheme.typography.labelLarge) Slider( value = value.toFloat(), onValueChange = { onValueChange(it.toInt()) }, valueRange = valueRange.first.toFloat()..valueRange.last.toFloat(), steps = valueRange.last - valueRange.first - 1 ) }}
@Preview(showBackground = true)@Preview(uiMode = Configuration.UI_MODE_NIGHT_YES, showBackground = true)@Composablefun PreviewServiceAreaControls() { SamplePreviewSurface { Surface { ServiceAreaControls( selectedGraphicType = GraphicType.Facility, onGraphicTypeSelected = {}, timeBreaks = TimeBreaks(3, 8), onShowTimeBreakDialog = {}, onSolveServiceArea = {}, onClearAll = {} ) } }}