Find 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 "STOPS" to add stops to find the route and display it. Tap "BARRIERS" to add areas that can't be crossed by the route. Tap the settings button to toggle preferences like find the best sequence or preserve the first or last stop. Additionally, tap the directions button to view a list of the directions. Tap any of the directions to focus the map view on the relevant part of the route. Press the reset button to start again.

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 createDefaultParameters() 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 returnStops and returnDirections 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.solveRoute(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 firstRoute.routeGeometry property.
    4. Create a graphic from the polyline and a simple line symbol.
    5. Display the steps on the route, available from firstRoute.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

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
/* Copyright 2023 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.findroutearoundbarriers

import android.graphics.drawable.BitmapDrawable
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.ImageView
import android.widget.ListView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.lifecycleScope
import com.arcgismaps.ApiKey
import com.arcgismaps.ArcGISEnvironment
import com.arcgismaps.Color
import com.arcgismaps.geometry.GeometryEngine
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.CompositeSymbol
import com.arcgismaps.mapping.symbology.HorizontalAlignment
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.TextSymbol
import com.arcgismaps.mapping.symbology.VerticalAlignment
import com.arcgismaps.mapping.view.Graphic
import com.arcgismaps.mapping.view.GraphicsOverlay
import com.arcgismaps.tasks.networkanalysis.DirectionManeuver
import com.arcgismaps.tasks.networkanalysis.PolygonBarrier
import com.arcgismaps.tasks.networkanalysis.RouteParameters
import com.arcgismaps.tasks.networkanalysis.RouteTask
import com.arcgismaps.tasks.networkanalysis.Stop
import com.esri.arcgismaps.sample.findroutearoundbarriers.databinding.ActivityMainBinding
import com.esri.arcgismaps.sample.findroutearoundbarriers.databinding.OptionsDialogBinding
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.button.MaterialButton
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.snackbar.Snackbar
import kotlinx.coroutines.launch

class MainActivity : AppCompatActivity() {

    // set up data binding for the activity
    private val activityMainBinding: ActivityMainBinding by lazy {
        DataBindingUtil.setContentView(this, R.layout.activity_main)
    }

    // show the options dialog
    private val optionsDialogBinding by lazy {
        OptionsDialogBinding.inflate(layoutInflater)
    }

    // set up the dialog UI views
    private val findBestSequenceSwitch by lazy {
        optionsDialogBinding.findBestSequenceSwitch
    }
    private val firstStopSwitch by lazy {
        optionsDialogBinding.firstStopSwitch
    }
    private val lastStopSwitch by lazy {
        optionsDialogBinding.lastStopSwitch
    }

    private val mapView by lazy {
        activityMainBinding.mapView
    }

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

    private val addStopsButton: MaterialButton by lazy {
        activityMainBinding.addStopsButton
    }

    private val addBarriersButton: MaterialButton by lazy {
        activityMainBinding.addBarriersButton
    }

    private val resetButton by lazy {
        activityMainBinding.resetButton
    }

    private val optionsButton by lazy {
        activityMainBinding.optionsButton
    }

    private val directionsButton by lazy {
        activityMainBinding.directionsButton
    }

    private val bottomSheet by lazy {
        activityMainBinding.directionSheet.directionSheetLayout
    }

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

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

    private val cancelTV: TextView by lazy {
        activityMainBinding.directionSheet.cancelTv
    }

    private val directionsLV: ListView by lazy {
        activityMainBinding.directionSheet.directionsLV
    }

    private val stopList by lazy { mutableListOf<Stop>() }

    private val barriersList by lazy { mutableListOf<PolygonBarrier>() }

    private val directionsList by lazy { mutableListOf<DirectionManeuver>() }

    private val stopsOverlay by lazy { GraphicsOverlay() }

    private val barriersOverlay by lazy { GraphicsOverlay() }

    private val routeOverlay: GraphicsOverlay by lazy { GraphicsOverlay() }

    private val barrierSymbol by lazy {
        SimpleFillSymbol(SimpleFillSymbolStyle.DiagonalCross, Color.red, null)
    }

    // create route task from San Diego service
    private val routeTask by lazy {
        RouteTask(getString(R.string.routing_service_url))
    }

    private var routeParameters: RouteParameters? = null

    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.API_KEY)
        // some parts of the API require an Android Context to properly interact with Android system
        // features, such as LocationProvider and application resources
        ArcGISEnvironment.applicationContext = applicationContext
        lifecycle.addObserver(mapView)

        // create and add a map with a navigation night basemap style
        mapView.apply {
            map = ArcGISMap(BasemapStyle.ArcGISStreets)
            setViewpoint(Viewpoint(32.7270, -117.1750, 40000.0))
            graphicsOverlays.addAll(listOf(stopsOverlay, barriersOverlay, routeOverlay))
        }

        // set an on touch listener on the map view
        lifecycleScope.launch {
            mapView.onSingleTapConfirmed.collect { event ->
                // add stop or barriers graphics to overlay
                event.mapPoint?.let { mapPoint -> addStopOrBarrier(mapPoint) }
                resetButton.isEnabled = true
            }
        }

        // coroutine scope to use the default parameters for the route calculation
        lifecycleScope.launch {
            routeTask.load().onSuccess {
                routeParameters = routeTask.createDefaultParameters().getOrThrow().apply {
                    returnStops = true
                    returnDirections = true
                }
            }.onFailure {
                showError(it.message.toString())
            }
        }

        // make a clear button to reset the stops and routes
        resetButton.setOnClickListener {
            // clear stops from route parameters and stops list
            routeParameters?.clearStops()
            stopList.clear()
            // clear barriers from route parameters and barriers list
            routeParameters?.clearPolygonBarriers()
            barriersList.clear()
            // clear the directions list
            directionsList.clear()
            // clear all graphics overlays
            mapView.graphicsOverlays.forEach { it.graphics.clear() }
            resetButton.isEnabled = false
        }

        // display the options dialog having the route finding parameters
        optionsButton.setOnClickListener {
            displayOptionsDialog()
        }

        // display the bottom sheet with directions when the button is clicked
        directionsButton.setOnClickListener {
            if (directionsList.isEmpty()) return@setOnClickListener showError("Add stops on map to find route")
            setupBottomSheet(directionsList)
        }

        // hide the bottom sheet and make the map view span the whole screen
        bottomSheet.visibility = View.INVISIBLE
        (mainContainer.layoutParams as CoordinatorLayout.LayoutParams).bottomMargin = 0
    }

    /**
     * Create options dialog with the route finding parameters to reorder stops to find the optimized route
     */
    private fun displayOptionsDialog() {
        // removes parent of the progressDialog layout, if previously assigned
        optionsDialogBinding.root.parent?.let { parent ->
            (parent as ViewGroup).removeAllViews()
        }

        // set up the dialog builder
        MaterialAlertDialogBuilder(this).apply {
            setView(optionsDialogBinding.root)
            show()
        }

        // set the best sequence toggle state
        findBestSequenceSwitch.isChecked = routeParameters?.findBestSequence ?: false

        // solve route on each state change
        findBestSequenceSwitch.setOnCheckedChangeListener { _, _ ->
            // update route params if the switch is toggled
            routeParameters?.findBestSequence = findBestSequenceSwitch.isChecked
            createAndDisplayRoute()

            // if best sequence switch is enabled, then enable the options
            if (findBestSequenceSwitch.isChecked) {
                firstStopSwitch.isEnabled = true
                lastStopSwitch.isEnabled = true

            } else {
                firstStopSwitch.apply {
                    isChecked = false
                    isEnabled = false
                }
                lastStopSwitch.apply {
                    isChecked = false
                    isEnabled = false
                }
            }
        }
        firstStopSwitch.setOnCheckedChangeListener { _, _ ->
            routeParameters?.preserveFirstStop = firstStopSwitch.isChecked
            createAndDisplayRoute()
        }
        lastStopSwitch.setOnCheckedChangeListener { _, _ ->
            routeParameters?.preserveLastStop = lastStopSwitch.isChecked
            createAndDisplayRoute()
        }
    }

    /**
     * Add a stop or a barrier at the selected [mapPoint] to the correct graphics
     * overlay depending on which button is currently checked.
     */
    private fun addStopOrBarrier(mapPoint: Point) {
        if (addStopsButton.isChecked) {
            // normalize the geometry - needed if the user crosses the international date line.
            val normalizedPoint = GeometryEngine.normalizeCentralMeridian(mapPoint) as Point
            // use the mapPoint to create a stop
            val stop = Stop(Point(normalizedPoint.x, normalizedPoint.y, mapPoint.spatialReference))
            // add the new stop to the list of stops
            stopList.add(stop)
            // create a marker symbol and graphics, and add the graphics to the graphics overlay
            stopsOverlay.graphics.add(Graphic(mapPoint, createStopSymbol(stopList.size)))
        } else if (addBarriersButton.isChecked) {
            // create a buffered polygon around the clicked point
            val barrierBufferPolygon = GeometryEngine.bufferOrNull(mapPoint, 200.0)
                ?: return showError("Error creating buffer polygon")
            // create a polygon barrier for the routing task, and add it to the list of barriers
            barriersList.add(PolygonBarrier(barrierBufferPolygon))
            barriersOverlay.graphics.add(Graphic(barrierBufferPolygon, barrierSymbol))
        }
        // solve the route once the graphics are created
        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() = lifecycleScope.launch {

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

        val routeParameters = routeParameters ?: return@launch

        if (stopList.size <= 1) return@launch

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

        // solve the route task
        val routeResults = routeParameters.let { routeTask.solveRoute(it) }

        routeResults.onSuccess { routeResult ->
            // get the first solved route
            val firstRoute = routeResult.routes[0]

            // create Graphic for route
            val graphic = Graphic(
                firstRoute.routeGeometry,
                SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.black, 3f)
            )
            routeOverlay.graphics.add(graphic)
            // get the direction text for each maneuver and add them to the list to display
            directionsList.addAll(firstRoute.directionManeuvers)
        }.onFailure {
            showError("No route solution. ${it.message}")
        }

    }

    /** Creates a bottom sheet to display a list of direction maneuvers.
     *  [directions] a list of DirectionManeuver which represents the route
     */
    private fun setupBottomSheet(directions: List<DirectionManeuver>) {
        val bottomSheetBehavior = BottomSheetBehavior.from(bottomSheet).apply {
            // expand the bottom sheet, and ensure it is displayed on the screen when collapsed
            state = BottomSheetBehavior.STATE_EXPANDED
            peekHeight = header.height
            // 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
                    }
                }
            })
        }

        bottomSheet.apply {
            visibility = View.VISIBLE
            // expand or collapse the bottom sheet when the header is clicked
            header.setOnClickListener {
                bottomSheetBehavior.state = when (bottomSheetBehavior.state) {
                    BottomSheetBehavior.STATE_COLLAPSED -> BottomSheetBehavior.STATE_EXPANDED
                    else -> BottomSheetBehavior.STATE_COLLAPSED
                }

            }
            // rotate the arrow so it starts off in the correct rotation
            imageView.rotation = 180f

            directionsLV.apply {
                // set the adapter for the list view
                adapter = ArrayAdapter(
                    this@MainActivity,
                    android.R.layout.simple_list_item_1,
                    directions.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 (routeOverlay.graphics.size > 1) {
                            routeOverlay.graphics.removeAt(routeOverlay.graphics.size - 1)
                        }
                        // set the viewpoint to the selected maneuver
                        val geometry = directionsList[position].geometry
                        geometry?.let { mapView.setViewpoint(Viewpoint(it.extent, 20.0)) }
                        // create a graphic with a symbol for the maneuver and add it to the graphics overlay
                        val selectedRouteSymbol = SimpleLineSymbol(
                            SimpleLineSymbolStyle.Solid,
                            Color.green, 3f
                        )
                        routeOverlay.graphics.add(Graphic(geometry, selectedRouteSymbol))
                        // collapse the bottom sheet
                        bottomSheetBehavior.state = BottomSheetBehavior.STATE_COLLAPSED
                    }
            }
            // hide the bottom sheet when cancel button is clicked
            cancelTV.setOnClickListener {
                bottomSheet.visibility = View.INVISIBLE
            }
        }

    }

    /**
     * Create a composite symbol consisting of a pin graphic overlaid with a particular [stopNumber].
     * Returns a [CompositeSymbol] consisting of the pin graphic overlaid with the stop number
     */
    private fun createStopSymbol(stopNumber: Int): CompositeSymbol {
        // create black stop number TextSymbol
        val stopNumberSymbol = TextSymbol(
            stopNumber.toString(),
            Color.black,
            12f,
            HorizontalAlignment.Center,
            VerticalAlignment.Bottom
        ).apply {
            offsetY = 4f
        }

        // create a new picture marker from a pin drawable
        val pinSymbol = PictureMarkerSymbol.createWithImage(
            ContextCompat.getDrawable(
                this,
                R.drawable.pin_symbol
            ) as BitmapDrawable
        ).apply {
            // set the scale of the symbol
            width = 24f
            height = 24f
            // set in pin "drop" to be offset to the point on map
            offsetY = 10f
        }

        // create a composite symbol and add the picture marker symbol and text symbol
        val compositeSymbol = CompositeSymbol()
        compositeSymbol.symbols.addAll(listOf(pinSymbol, stopNumberSymbol))

        return compositeSymbol
    }

    private fun showError(message: String) {
        Log.e(localClassName, message)
        Snackbar.make(mapView, message, Snackbar.LENGTH_SHORT).show()
    }
}

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