Route around barriers

View on GitHubSample viewer app

Find a route that reaches all stops without crossing any barriers.

Image of route around barriers

Use case

You can define barriers to avoid unsafe areas, for example flooded roads, when planning the most efficient route to evacuate a hurricane zone. When solving a route, barriers allow you to define portions of the road network that cannot be traversed. You could also use this functionality to plan routes when you know an area will be inaccessible due to a community activity like an organized race or a market night.

In some situations, it is further beneficial to find the most efficient route that reaches all stops, reordering them to reduce travel time. For example, a delivery service may target a number of drop-off addresses, specifically looking to avoid congested areas or closed roads, arranging the stops in the most time-effective order.

How to use the sample

Tap 'Route controls' to pull up a bottom sheet that contains UI to setup your route task parameters. Click 'Add stop' to add stops to the route. Click 'Add barrier' to add areas that can't be crossed by the route. Click 'Solve route' to find the route and display it. Check 'Allow stops to be re-ordered' to find the best sequence. Check 'Preserve first stop' if there is a known start point, and 'Preserve last stop' if there is a known final destination. Press the reset button to start again.

After tapping 'solve route' the bottom sheet will show a list of directions along the route. Tap any of the directions to focus the map view on the relevant part of the route.

How it works

  1. Create the route task by calling RouteTask with a URL to a Network Analysis route service.
  2. Get the default route parameters for the service by calling createDefaultParametersAsync() on the route task.
  3. When the user adds a stop, add it to the route parameters.
    1. Normalize the geometry; otherwise the route job would fail if the user included any stops over the 180th degree meridian.
    2. Get the name of the stop by counting the existing stops - stopList.size.
    3. Create a composite symbol for the stop. This sample uses a pushpin marker and a text symbol.
    4. Create the graphic from the geometry and the symbol.
    5. Add the graphic to the stops graphics overlay.
  4. When the user adds a barrier, create a polygon barrier and add it to the route parameters.
    1. Normalize the geometry (see 3i above).
    2. Buffer the geometry to create a larger barrier from the tapped point by calling GeometryEngine.buffer(mapPoint, 500.0).
    3. Create the graphic from the geometry and the symbol.
    4. Add the graphic to the barriers overlay.
  5. When ready to find the route, configure the route parameters.
    1. Set the isReturnStops and isReturnDirections to true.
    2. Create a Stop for each graphic in the stops graphics overlay. Add that stop to a list, then call setStops(stopList).
    3. Create a PolygonBarrier for each graphic in the barriers graphics overlay. Add that barrier to a list, then call setPolygonBarriers(barrierList).
    4. If the user will accept routes with the stops in any order, set findBestSequence to true to find the most optimal route.
    5. If the user has a definite start point, set preserveFirstStop to true.
    6. If the user has a definite final destination, set preserveLastStop to true.
  6. Calculate and display the route.
    1. Call routeTask.solveRouteAsync(routeParameters) to get a RouteResult.
    2. Get the first returned route by calling routeResult.routes[0].
    3. Get the geometry from the route, as a polyline, by accessing the firstResult.routeGeometry property.
    4. Create a graphic from the polyline and a simple line symbol.
    5. Display the steps on the route, available from firstResult.directionManeuvers.

Relevant API

  • DirectionManeuver
  • PolygonBarrier
  • Route
  • Route.DirectionManeuver
  • Route.RouteGeometry
  • RouteParameters.ClearPolygonBarriers
  • RouteParameters.FindBestSequence
  • RouteParameters.PreserveFirstStop
  • RouteParameters.PreserveLastStop
  • RouteParameters.ReturnDirections
  • RouteParameters.ReturnStops
  • RouteParameters.SetPolygonBarriers
  • RouteResult
  • RouteResult.Routes
  • RouteTask
  • Stop
  • Stop.Name

About the data

This sample uses an Esri-hosted sample street network for San Diego.

Tags

barriers, best sequence, directions, maneuver, network analysis, routing, sequence, stop order, stops

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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
/*
 * 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.routearoundbarriers

import android.graphics.Color
import android.graphics.drawable.BitmapDrawable
import android.os.Bundle
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.view.View.GONE
import android.view.View.VISIBLE
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.content.ContextCompat
import com.esri.arcgisruntime.ArcGISRuntimeEnvironment
import com.esri.arcgisruntime.geometry.GeometryEngine
import com.esri.arcgisruntime.geometry.Point
import com.esri.arcgisruntime.loadable.LoadStatus
import com.esri.arcgisruntime.mapping.ArcGISMap
import com.esri.arcgisruntime.mapping.BasemapStyle
import com.esri.arcgisruntime.mapping.Viewpoint
import com.esri.arcgisruntime.mapping.view.DefaultMapViewOnTouchListener
import com.esri.arcgisruntime.mapping.view.Graphic
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay
import com.esri.arcgisruntime.mapping.view.MapView
import com.esri.arcgisruntime.sample.routearoundbarriers.databinding.ActivityMainBinding
import com.esri.arcgisruntime.symbology.CompositeSymbol
import com.esri.arcgisruntime.symbology.PictureMarkerSymbol
import com.esri.arcgisruntime.symbology.SimpleFillSymbol
import com.esri.arcgisruntime.symbology.SimpleLineSymbol
import com.esri.arcgisruntime.symbology.SimpleRenderer
import com.esri.arcgisruntime.symbology.TextSymbol
import com.esri.arcgisruntime.tasks.networkanalysis.DirectionManeuver
import com.esri.arcgisruntime.tasks.networkanalysis.PolygonBarrier
import com.esri.arcgisruntime.tasks.networkanalysis.Route
import com.esri.arcgisruntime.tasks.networkanalysis.RouteParameters
import com.esri.arcgisruntime.tasks.networkanalysis.RouteResult
import com.esri.arcgisruntime.tasks.networkanalysis.RouteTask
import com.esri.arcgisruntime.tasks.networkanalysis.Stop
import com.google.android.material.bottomsheet.BottomSheetBehavior
import kotlin.math.roundToInt

class MainActivity : AppCompatActivity() {

    private val TAG: String = MainActivity::class.java.simpleName

    private var bottomSheetBehavior: BottomSheetBehavior<View>? = null

    private var routeTask: RouteTask? = null
    private var routeParameters: RouteParameters? = null
    private var pinSymbol: PictureMarkerSymbol? = null

    private val routeGraphicsOverlay by lazy { GraphicsOverlay() }
    private val stopsGraphicsOverlay by lazy { GraphicsOverlay() }
    private val barriersGraphicsOverlay by lazy { GraphicsOverlay() }

    private val stopList by lazy { mutableListOf<Stop>() }
    private val barrierList by lazy { mutableListOf<PolygonBarrier>() }
    private val directionsList by lazy { mutableListOf<DirectionManeuver>() }

    private val routeLineSymbol by lazy {
        SimpleLineSymbol(
            SimpleLineSymbol.Style.SOLID,
            Color.BLUE,
            5.0f
        )
    }
    private val barrierSymbol by lazy {
        SimpleFillSymbol(
            SimpleFillSymbol.Style.DIAGONAL_CROSS,
            Color.RED,
            null
        )
    }

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

    private val mapView: MapView by lazy {
        activityMainBinding.mapView
    }

    private val mapViewContainer: ConstraintLayout by lazy {
        activityMainBinding.mapViewContainer
    }

    private val resetButton: Button by lazy {
        activityMainBinding.resetButton
    }

    private val bottomSheet: LinearLayout by lazy {
        activityMainBinding.bottomSheet.bottomSheetLayout
    }

    private val header: ConstraintLayout by lazy {
        activityMainBinding.bottomSheet.header
    }

    private val imageView: ImageView by lazy {
        activityMainBinding.bottomSheet.imageView
    }

    private val addStopButton: ToggleButton by lazy {
        activityMainBinding.bottomSheet.addStopButton
    }

    private val addBarrierButton: ToggleButton by lazy {
        activityMainBinding.bottomSheet.addBarrierButton
    }

    private val reorderCheckBox: CheckBox by lazy {
        activityMainBinding.bottomSheet.reorderCheckBox
    }

    private val preserveFirstStopCheckBox: CheckBox by lazy {
        activityMainBinding.bottomSheet.preserveFirstStopCheckBox
    }

    private val preserveLastStopCheckBox: CheckBox by lazy {
        activityMainBinding.bottomSheet.preserveLastStopCheckBox
    }

    private val directionsTextView: TextView by lazy {
        activityMainBinding.bottomSheet.directionsTextView
    }

    private val directionsListView: ListView by lazy {
        activityMainBinding.bottomSheet.directionsListView
    }

    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 simple renderer for routes, and set it to use the line symbol
        routeGraphicsOverlay.renderer = SimpleRenderer().apply {
            symbol = routeLineSymbol
        }

        mapView.apply {
            // add a map with the streets basemap to the map view, centered on San Diego
            map = ArcGISMap(BasemapStyle.ARCGIS_STREETS)
            // center on San Diego
            setViewpoint(Viewpoint(32.7270, -117.1750, 40000.0))
            // add the graphics overlays to the map view
            graphicsOverlays.addAll(
                listOf(stopsGraphicsOverlay, barriersGraphicsOverlay, routeGraphicsOverlay)
            )
            onTouchListener = object : DefaultMapViewOnTouchListener(this@MainActivity, mapView) {
                override fun onSingleTapConfirmed(motionEvent: MotionEvent): Boolean {
                    val screenPoint =
                        android.graphics.Point(
                            motionEvent.x.roundToInt(),
                            motionEvent.y.roundToInt()
                        )
                    addStopOrBarrier(screenPoint)
                    return true
                }
            }
        }

        // create a new picture marker from a pin drawable
        pinSymbol = PictureMarkerSymbol.createAsync(
            ContextCompat.getDrawable(
                this,
                R.drawable.pin_symbol
            ) as BitmapDrawable
        ).get().apply {
            width = 30f
            height = 30f
            offsetY = 20f
        }

        // create route task from San Diego service
        routeTask = RouteTask(
            this,
            "https://sampleserver6.arcgisonline.com/arcgis/rest/services/NetworkAnalysis/SanDiego/NAServer/Route"
        ).apply {
            addDoneLoadingListener {
                if (loadStatus == LoadStatus.LOADED) {
                    // get default route parameters
                    val routeParametersFuture = createDefaultParametersAsync()
                    routeParametersFuture.addDoneListener {
                        try {
                            routeParameters = routeParametersFuture.get().apply {
                                // set flags to return stops and directions
                                isReturnStops = true
                                isReturnDirections = true
                            }
                        } catch (e: Exception) {
                            Log.e(TAG, "Cannot create RouteTask parameters " + e.message)
                        }
                    }
                } else {
                    Log.e(TAG, "Unable to load RouteTask $loadStatus")
                }
            }
        }
        routeTask?.loadAsync()


        // shrink the map view so it is not hidden under the bottom sheet header
        bottomSheetBehavior = BottomSheetBehavior.from(bottomSheet)
        (mapViewContainer.layoutParams as CoordinatorLayout.LayoutParams).bottomMargin =
            (bottomSheetBehavior as BottomSheetBehavior<View>).peekHeight
        bottomSheetBehavior?.state = BottomSheetBehavior.STATE_EXPANDED

        bottomSheet.apply {
            // expand or collapse the bottom sheet when the header is clicked
            header.setOnClickListener {
                bottomSheetBehavior?.state = when (bottomSheetBehavior?.state) {
                    BottomSheetBehavior.STATE_COLLAPSED -> BottomSheetBehavior.STATE_HALF_EXPANDED
                    else -> BottomSheetBehavior.STATE_COLLAPSED
                }
            }
            // rotate the arrow so it starts off in the correct rotation
            imageView.rotation = 180f
        }

        // change button toggle state on click
        addStopButton.setOnClickListener { addBarrierButton.isChecked = false }
        addBarrierButton.setOnClickListener { addStopButton.isChecked = false }

        // solve route on checkbox change state
        reorderCheckBox.setOnCheckedChangeListener { _, _ -> createAndDisplayRoute() }
        preserveFirstStopCheckBox.setOnCheckedChangeListener { _, _ -> createAndDisplayRoute() }
        preserveLastStopCheckBox.setOnCheckedChangeListener { _, _ -> createAndDisplayRoute() }

        // start sample with add stop button true
        addStopButton.isChecked = true
    }

    /**
     * Add a stop or a point to the correct graphics overlay depending on which button is currently
     * checked.
     *
     * @param screenPoint at which to create a stop or point
     */
    private fun addStopOrBarrier(screenPoint: android.graphics.Point) {
        // convert screen point to map point
        val mapPoint = mapView.screenToLocation(screenPoint)
        // normalize geometry - important for geometries that will be sent to a server for processing
        val normalizedPoint = GeometryEngine.normalizeCentralMeridian(mapPoint) as Point
        // clear the displayed route, if it exists, since it might not be up to date any more
        routeGraphicsOverlay.graphics.clear()
        if (addStopButton.isChecked) {
            // use the clicked map point to construct a stop
            val stopPoint =
                Stop(Point(normalizedPoint.x, normalizedPoint.y, mapPoint.spatialReference))
            // add the new stop to the list of stops
            stopList.add(stopPoint)
            // create a marker symbol and graphics, and add the graphics to the graphics overlay
            stopsGraphicsOverlay.graphics.add(
                Graphic(
                    mapPoint,
                    createCompositeStopSymbol(stopList.size)
                )
            )
        } else if (addBarrierButton.isChecked) {
            // create a buffered polygon around the clicked point
            val bufferedBarrierPolygon = GeometryEngine.buffer(mapPoint, 200.0)
            // create a polygon barrier for the routing task, and add it to the list of barriers
            barrierList.add(PolygonBarrier(bufferedBarrierPolygon))
            // build graphics for the barrier and add it to the graphics overlay
            barriersGraphicsOverlay.graphics.add(Graphic(bufferedBarrierPolygon, barrierSymbol))
        }
        createAndDisplayRoute()
    }

    /**
     * Create route parameters and a route task from them. Display the route result geometry as a
     * graphic and call showDirectionsInBottomSheet which shows directions in a list view.
     */
    private fun createAndDisplayRoute() {
        if (stopList.size < 2) {
            // clear the directions list since no route is displayed
            directionsList.clear()
            return
        }

        // clear the previous route from the graphics overlay, if it exists
        routeGraphicsOverlay.graphics.clear()
        // clear the directions list from the directions list view, if they exist
        directionsList.clear()

        routeParameters?.apply {
            // add the existing stops and barriers to the route parameters
            setStops(stopList)
            setPolygonBarriers(barrierList)

            // apply the requested route finding parameters
            isFindBestSequence = reorderCheckBox.isChecked
            isPreserveFirstStop = preserveFirstStopCheckBox.isChecked
            isPreserveLastStop = preserveLastStopCheckBox.isChecked
        }

        // solve the route task
        val routeResultFuture = routeTask?.solveRouteAsync(routeParameters)
        routeResultFuture?.addDoneListener {
            try {
                val routeResult: RouteResult = routeResultFuture.get()
                if (routeResult.routes.isNotEmpty()) {
                    // get the first route result
                    val firstRoute: Route = routeResult.routes[0]

                    // create a graphic for the route and add it to the graphics overlay
                    val routeGraphic = Graphic(firstRoute.routeGeometry)
                    routeGraphicsOverlay.graphics.add(routeGraphic)

                    // get the direction text for each maneuver and add them to the list to display
                    directionsList.addAll(firstRoute.directionManeuvers)

                    showDirectionsInBottomSheet()
                } else {
                    Toast.makeText(this, "No routes found.", Toast.LENGTH_LONG).show()
                }
            } catch (e: Exception) {
                val error = "Solve route task failed: " + e.message
                Log.e(TAG, error)
                Toast.makeText(this, error, Toast.LENGTH_LONG).show()
            }

            // show the reset button
            resetButton.visibility = VISIBLE
        }
    }

    /**
     * Clear all stops and polygon barriers from the route parameters, stop and barrier
     * lists and all graphics overlays. Also hide the directions list view and show the control
     * layout.
     *
     * @param reset button which calls this method
     */
    fun clearRouteAndGraphics(reset: View) {
        // clear stops from route parameters and stops list
        routeParameters?.clearStops()
        stopList.clear()
        // clear barriers from route parameters and barriers list
        routeParameters?.clearPolygonBarriers()
        barrierList.clear()
        // clear the directions list
        directionsList.clear()
        // clear all graphics overlays
        mapView.graphicsOverlays.forEach { it.graphics.clear() }
        // hide the reset button and directions list
        resetButton.visibility = GONE
        // hide the directions
        directionsTextView.visibility = GONE
        directionsListView.visibility = GONE
    }

    /**
     * Create a composite symbol consisting of a pin graphic overlaid with a particular stop number.
     *
     * @param stopNumber to overlay the pin symbol
     * @return a composite symbol consisting of the pin graphic overlaid with an the stop number
     */
    private fun createCompositeStopSymbol(stopNumber: Int): CompositeSymbol {
        // determine the stop number and create a new label
        val stopTextSymbol = TextSymbol(
            16f,
            stopNumber.toString(),
            -0x1,
            TextSymbol.HorizontalAlignment.CENTER,
            TextSymbol.VerticalAlignment.BOTTOM
        )
        stopTextSymbol.offsetY = pinSymbol?.height as Float / 2
        // construct a composite symbol out of the pin and text symbols, and return it
        return CompositeSymbol(listOf(pinSymbol, stopTextSymbol))
    }

    /**
     * Creates a bottom sheet to display a list of direction maneuvers.
     */
    private fun showDirectionsInBottomSheet() {
        // show the directions list view
        directionsTextView.visibility = VISIBLE
        directionsListView.visibility = VISIBLE
        // create a bottom sheet behavior from the bottom sheet view in the main layout
        bottomSheetBehavior?.apply {
            // animate the arrow when the bottom sheet slides
            addBottomSheetCallback(object : BottomSheetBehavior.BottomSheetCallback() {
                override fun onSlide(bottomSheet: View, slideOffset: Float) {
                    imageView.rotation = slideOffset * 180f
                }

                override fun onStateChanged(bottomSheet: View, newState: Int) {
                    imageView.rotation = when (newState) {
                        BottomSheetBehavior.STATE_EXPANDED -> 180f
                        else -> imageView.rotation
                    }
                }
            })
        }

        directionsListView.apply {
            // Set the adapter for the list view
            adapter = ArrayAdapter(
                this@MainActivity,
                android.R.layout.simple_list_item_1,
                directionsList.map { it.directionText })
            // when the user taps a maneuver, set the viewpoint to that portion of the route
            onItemClickListener =
                AdapterView.OnItemClickListener { _, _, position, _ ->
                    // remove any graphics that are not the original (blue) route graphic
                    if (routeGraphicsOverlay.graphics.size > 1) {
                        routeGraphicsOverlay.graphics.removeAt(routeGraphicsOverlay.graphics.size - 1)
                    }
                    // set the viewpoint to the selected maneuver
                    val geometry = directionsList[position].geometry
                    mapView.setViewpointAsync(Viewpoint(geometry.extent, 20.0), 1f)
                    // create a graphic with a symbol for the maneuver and add it to the graphics overlay
                    val selectedRouteSymbol = SimpleLineSymbol(
                        SimpleLineSymbol.Style.SOLID,
                        Color.GREEN, 5f
                    )
                    routeGraphicsOverlay.graphics.add(Graphic(geometry, selectedRouteSymbol))
                    // collapse the bottom sheet
                    bottomSheetBehavior?.state = BottomSheetBehavior.STATE_COLLAPSED
                }
            // allow the list view to scroll within bottom sheet
            isNestedScrollingEnabled = true
        }
    }

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

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

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

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