Create a notification every time a given location data source has entered and/or exited a set of features or graphics.

Use case
Geotriggers can be used to notify users when they have entered or exited a geofence by monitoring a given set of features or graphics. They could be used to display contextual information to museum visitors about nearby exhibits, notify hikers when they have wandered off their desired trail, notify dispatchers when service workers arrive at a scene, or more.
How to use the sample
Observe a virtual walking tour of the Santa Barbara Botanic Garden. Information about the user’s current Garden Section, as well as information about nearby points of interest within 10 meters will display or be removed from the UI when the user enters or exits the buffer of each feature.
How it works
- Create a
GeotriggerFeedwith aLocationDataSourceclass (in this case, aSimulatedLocationDataSource). - Create a
FeatureFenceParametersclass from aServiceFeatureTable, a buffer distance at which to monitor each feature, an Arcade Expression, and a name for the specific geotrigger. - Create a
FenceGeotriggerwith the geotrigger feed, aFenceRuleType, and the fence parameters. - Create a
GeotriggerMonitorwith the fence geotrigger and callGeotriggerMonitor.start()to begin listening for events that meet theFenceRuleType. - When
GeotriggerMonitor.geotriggerNotificationemits, capture theGeotriggerNotificationInfo. - For more information about the feature that triggered the notification, cast the
GeotriggerNotificationInfoto aFenceGeotriggerNotificationInfoand callFenceGeotriggerNotificationInfo.fenceGeoElement. - Depending on the
FenceGeotriggerNotificationInfo.fenceNotificationTypedisplay or hide information on the UI from theGeoElement’s attributes.
Relevant API
- ArcadeExpression
- FeatureFenceParameters
- FenceGeotrigger
- FenceGeotriggerNotificationInfo
- FenceRuleType
- GeoElement
- Geotrigger
- GeotriggerFeed
- GeotriggerMonitor
- GeotriggerNotificationInfo
- ServiceFeatureTable
- SimulatedLocationDataSource
About the data
This sample uses the Santa Barbara Botanic Garden Geotriggers Sample ArcGIS Online Web Map which includes a georeferenced map of the garden as well as select polygon and point features to denote garden sections and points of interest. Description text and attachment images in the feature layers were provided by the Santa Barbara Botanic Garden and more information can be found on the Garden Sections & Displays portion of their website. All assets are used with permission from the Santa Barbara Botanic Garden. For more information, visit the Santa Barbara Botanic Garden website.
Tags
alert, arcade, fence, geofence, geotrigger, location, navigation, notification, notify, routing, trigger
Sample Code
/* * 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.setuplocationdrivengeotriggers
import android.view.LayoutInflaterimport android.view.Viewimport android.view.ViewGroupimport android.widget.TextViewimport androidx.recyclerview.widget.RecyclerViewimport androidx.recyclerview.widget.RecyclerView.ViewHolderimport com.arcgismaps.data.ArcGISFeature
/** * Provides a reference view holder to a custom view type * for the FeatureListAdapter */class FeatureViewHolder(view: View) : ViewHolder(view) { // shows the title information val titleView: TextView by lazy { view.findViewById(R.id.featureNameTextView) }}
/** * Custom RecyclerView Adapter to display the list of points of interests [featuresList] * [onItemClickListener] event is called when an itemView clicks */class FeatureListAdapter( private val featuresList: List<ArcGISFeature>, private var onItemClickListener: (ArcGISFeature) -> Unit) : RecyclerView.Adapter<FeatureViewHolder>() {
override fun onBindViewHolder(holder: FeatureViewHolder, position: Int) { // bind the feature information to each item view val feature = featuresList[position] // set the title holder.titleView.text = feature.attributes["name"].toString() // set the onClickListener to pass the item's feature holder.titleView.setOnClickListener { onItemClickListener(feature) } }
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FeatureViewHolder { // inflate the item's view with the layout resource val view = LayoutInflater.from(parent.context) .inflate(R.layout.feature_list_item, parent, false) return FeatureViewHolder(view) }
override fun getItemCount(): Int { return featuresList.size }}/* * 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.setuplocationdrivengeotriggers
import android.content.DialogInterfaceimport android.graphics.BitmapFactoryimport android.os.Bundleimport android.view.LayoutInflaterimport android.view.Viewimport android.view.ViewGroupimport androidx.lifecycle.lifecycleScopeimport com.arcgismaps.data.ArcGISFeatureimport com.esri.arcgismaps.sample.setuplocationdrivengeotriggers.databinding.FragmentFeatureViewBindingimport com.google.android.material.bottomsheet.BottomSheetDialogFragmentimport kotlinx.coroutines.launch
/** * Class to display an ArcGISFeature [featureSection] information as a * bottom sheet dialog fragment. Provides an [onDismissListener] callback * when the fragment is dismissed. */class FeatureViewFragment( private val featureSection: ArcGISFeature, private val onDismissListener: () -> Unit) : BottomSheetDialogFragment() {
// setup binding for the fragment private val featureViewFragmentBinding by lazy { FragmentFeatureViewBinding.inflate(layoutInflater) }
// displays the feature title private val contentTitleText by lazy { featureViewFragmentBinding.contentTitleTextView }
// displays the feature description private val contentDescriptionText by lazy { featureViewFragmentBinding.contentDescriptionTextView }
// displays the primary image attachment of the feature private val contentImage by lazy { featureViewFragmentBinding.contentImageView }
override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { // Inflate the layout for this fragment return featureViewFragmentBinding.root }
override fun onStart() { super.onStart() // set up the UI // set the title text to the feature name contentTitleText.text = featureSection.attributes["name"] as String // set the description text to the feature description contentDescriptionText.text = featureSection.attributes["desc_raw"] as String // load the feature attachments loadAttachments() }
override fun onDismiss(dialog: DialogInterface) { super.onDismiss(dialog) // call the dismiss listener onDismissListener() }
/** * Loads the attachments of this ArcGISFeature and updates the UI */ private fun loadAttachments() = lifecycleScope.launch { // fetch the list of attachments val attachments = featureSection.fetchAttachments().getOrElse { // return if it fails return@launch } // if there are attachments if (attachments.isNotEmpty()) { // get the first (and only) attachment for the feature, which is an image val imageAttachment = attachments.first() // and fetch its data val imageData = imageAttachment.fetchData().getOrElse { // return if it fails return@launch } // construct a bitmap from the fetched image data val bitmap = BitmapFactory.decodeByteArray(imageData, 0, imageData.size) // set the bitmap to the imageview contentImage.setImageBitmap(bitmap) } }}/* * 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.setuplocationdrivengeotriggers
import android.os.Bundleimport android.util.Logimport android.widget.Toastimport com.esri.arcgismaps.sample.sampleslib.EdgeToEdgeCompatActivityimport androidx.databinding.DataBindingUtilimport androidx.lifecycle.lifecycleScopeimport androidx.recyclerview.widget.LinearLayoutManagerimport com.arcgismaps.ApiKeyimport com.arcgismaps.ArcGISEnvironmentimport com.arcgismaps.arcade.ArcadeExpressionimport com.arcgismaps.data.ArcGISFeatureimport com.arcgismaps.data.ServiceFeatureTableimport com.arcgismaps.geometry.Geometryimport com.arcgismaps.geometry.Polylineimport com.arcgismaps.geotriggers.FeatureFenceParametersimport com.arcgismaps.geotriggers.FenceGeotriggerimport com.arcgismaps.geotriggers.FenceGeotriggerNotificationInfoimport com.arcgismaps.geotriggers.FenceNotificationTypeimport com.arcgismaps.geotriggers.FenceRuleTypeimport com.arcgismaps.geotriggers.GeotriggerMonitorimport com.arcgismaps.geotriggers.GeotriggerNotificationInfoimport com.arcgismaps.geotriggers.LocationGeotriggerFeedimport com.arcgismaps.location.LocationDataSourceStatusimport com.arcgismaps.location.LocationDisplayAutoPanModeimport com.arcgismaps.location.SimulatedLocationDataSourceimport com.arcgismaps.location.SimulationParametersimport com.arcgismaps.mapping.ArcGISMapimport com.arcgismaps.mapping.PortalItemimport com.arcgismaps.portal.Portalimport com.esri.arcgismaps.sample.setuplocationdrivengeotriggers.databinding.SetUpLocationDrivenGeotriggersActivityMainBindingimport com.google.android.material.button.MaterialButtonimport com.google.android.material.floatingactionbutton.FloatingActionButtonimport com.google.android.material.snackbar.Snackbarimport kotlinx.coroutines.launchimport java.time.Instant
class MainActivity : EdgeToEdgeCompatActivity() {
// set up data binding for the activity private val activityMainBinding: SetUpLocationDrivenGeotriggersActivityMainBinding by lazy { DataBindingUtil.setContentView(this, R.layout.set_up_location_driven_geotriggers_activity_main) }
private val mapView by lazy { activityMainBinding.mapView }
private val playPauseFAB: FloatingActionButton by lazy { activityMainBinding.playPauseFAB }
private val sectionButton: MaterialButton by lazy { activityMainBinding.sectionButton }
// recycler list view to show the the points of interest private val poiListView by lazy { activityMainBinding.poiListView }
// custom list adapter for the points of interest private val poiListAdapter by lazy { // create a new feature list adapter from the poiList FeatureListAdapter(poiList) { feature -> // set the item callback to show the feature view fragment showFeatureViewFragment(feature) } }
private val simulatedLocationDataSource: SimulatedLocationDataSource by lazy { // create SimulationParameters starting at the current time, // a velocity of 10 m/s, and a horizontal and vertical accuracy of 0.0 val simulationParameters = SimulationParameters( Instant.now(), velocity = 3.0, horizontalAccuracy = 0.0, verticalAccuracy = 0.0 ) // create a SimulatedLocationDataSource using the polyline from // ArcGIS Online GeoJSON to define the path. retrieved from // https://arcgisruntime.maps.arcgis.com/home/item.html?id=2a346cf1668d4564b8413382ae98a956 SimulatedLocationDataSource( Geometry.fromJsonOrNull(getString(R.string.polyline_json)) as Polyline, simulationParameters ) }
// feature list to store the points of interest of a geotrigger private val poiList = mutableListOf<ArcGISFeature>()
// geotrigger names for the geotrigger monitors private val sectionGeotrigger = "Section Geotrigger" private val poiGeotrigger = "POI Geotrigger"
// make monitors properties to prevent garbage collection private lateinit var sectionGeotriggerMonitor: GeotriggerMonitor private lateinit var poiGeotriggerMonitor: GeotriggerMonitor
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) lifecycle.addObserver(mapView)
val portal = Portal("https://www.arcgis.com") // this sample uses a web map with a predefined tile basemap, feature styles, and labels val map = ArcGISMap(PortalItem(portal, "6ab0e91dc39e478cae4f408e1a36a308")) // set the mapview's map mapView.map = map // set the map to display the location of the simulatedLocationDataSource mapView.locationDisplay.apply { dataSource = simulatedLocationDataSource setAutoPanMode(LocationDisplayAutoPanMode.Recenter) initialZoomScale = 1000.0 }
// instantiate the service feature tables to later create GeotriggerMonitors for val gardenSections = ServiceFeatureTable(PortalItem(portal, "1ba816341ea04243832136379b8951d9"), 0) val gardenPOIs = ServiceFeatureTable(PortalItem(portal, "7c6280c290c34ae8aeb6b5c4ec841167"), 0) // create geotriggers for each of the service feature tables sectionGeotriggerMonitor = createGeotriggerMonitor(gardenSections, 0.0, sectionGeotrigger) poiGeotriggerMonitor = createGeotriggerMonitor(gardenPOIs, 10.0, poiGeotrigger)
// play or pause the simulation data source when the FAB is clicked playPauseFAB.setOnClickListener { when (simulatedLocationDataSource.status.value) { LocationDataSourceStatus.Started -> { stopSimulatedDataSource(true) } LocationDataSourceStatus.Stopped -> { startSimulatedDataSource(true) } else -> { // show an error if the status is anything else showError( "Error modifying location data source state: " + "${simulatedLocationDataSource.status.value}" ) } } }
// set the recycler view layout to a vertical linear layout poiListView.layoutManager = LinearLayoutManager(this) // assign its adapter poiListView.adapter = poiListAdapter
lifecycleScope.launch { // wait for the map load map.load().onFailure { // if the map load fails, show the error and return showError("Error loading map: ${it.message}") return@launch } // start the section geotrigger monitor sectionGeotriggerMonitor.start().onFailure { // if the monitor start fails, show the error and return showError("Section Geotrigger Monitor failed to start: ${it.message}") return@launch } // start the points of interest geotrigger monitor poiGeotriggerMonitor.start().onFailure { // if the monitor start fails, show the error and return showError("POI Geotrigger Monitor failed to start: ${it.message}") return@launch } // finally, start the simulated location data source simulatedLocationDataSource.start().onFailure { // if it fails, show the error and return showError("Simulated Location DataSource failed to start: ${it.message}") } } }
/** * Creates and returns a geotrigger monitor with the [geotriggerName] name, * using the [serviceFeatureTable] and [bufferSize] to initialize * FeatureFenceParameters for the geotrigger */ private fun createGeotriggerMonitor( serviceFeatureTable: ServiceFeatureTable, bufferSize: Double, geotriggerName: String ): GeotriggerMonitor { // create a LocationGeotriggerFeed that uses the SimulatedLocationDataSource val geotriggerFeed = LocationGeotriggerFeed(simulatedLocationDataSource) // initialize FeatureFenceParameters to display the section the user has entered val featureFenceParameters = FeatureFenceParameters(serviceFeatureTable, bufferSize) // create a fence geotrigger val fenceGeotrigger = FenceGeotrigger( geotriggerFeed, // triggers on enter/exit FenceRuleType.EnterOrExit, featureFenceParameters, // arcade expression to get the feature name ArcadeExpression("\$fenceFeature.name"), geotriggerName )
// initialize a geotrigger monitor with the fence geotrigger val geotriggerMonitor = GeotriggerMonitor(fenceGeotrigger) lifecycleScope.launch { // capture and handle geotrigger notification based on the FenceRuleType // hence, triggers on fence enter/exit. geotriggerMonitor.notifications.collect { geotriggerNotificationInfo -> handleGeotriggerNotification(geotriggerNotificationInfo) } } return geotriggerMonitor }
/** * Handles the [geotriggerNotificationInfo] based on its geotrigger type * and FenceNotificationType */ private fun handleGeotriggerNotification(geotriggerNotificationInfo: GeotriggerNotificationInfo) { // cast it to FenceGeotriggerNotificationInfo which provides // access to the feature that triggered the notification val fenceGeotriggerNotificationInfo = geotriggerNotificationInfo as FenceGeotriggerNotificationInfo // name of the fence feature, returned from the set arcade expression val fenceFeatureName = fenceGeotriggerNotificationInfo.message // get the specific geotrigger name we set during initialization val geotriggerType = fenceGeotriggerNotificationInfo.geotriggerMonitor.geotrigger.name // check for the type of notification when (fenceGeotriggerNotificationInfo.fenceNotificationType) { FenceNotificationType.Entered -> { // if the user location entered the geofence, add the feature information to the UI addFeatureInformation( fenceFeatureName, geotriggerType, fenceGeotriggerNotificationInfo.fenceGeoElement as ArcGISFeature ) } FenceNotificationType.Exited -> { // if the user exits a given geofence, remove the feature's information from the UI removeFeatureInformation(fenceFeatureName, geotriggerType) } } }
/** * Adds the [fenceFeature] ArcGISFeature with the [fenceFeatureName] and [geotriggerType] to the current UI state * and refreshes the UI */ private fun addFeatureInformation( fenceFeatureName: String, geotriggerType: String, fenceFeature: ArcGISFeature ) { // recenter the mapview mapView.locationDisplay.setAutoPanMode(LocationDisplayAutoPanMode.Recenter)
when (geotriggerType) { // if it's a section geo trigger type sectionGeotrigger -> { // update the section button's onClickListener // to show a new FeatureViewFragment sectionButton.setOnClickListener { showFeatureViewFragment(fenceFeature) } // update the section button text to the feature name sectionButton.text = fenceFeatureName // enable the button sectionButton.isEnabled = true } // or a point of interest geo trigger poiGeotrigger -> { // add it to the stored list poiList.add(fenceFeature) // notify the list adapter to refresh its recycler views poiListAdapter.notifyItemInserted(poiList.lastIndex) } } }
/** * Removes the ArcGISFeature with the given [fenceFeatureName] and corresponding * [geotriggerType] from the current UI state and refreshes the UI. */ private fun removeFeatureInformation(fenceFeatureName: String, geotriggerType: String) { // check the type of geotrigger when (geotriggerType) { sectionGeotrigger -> { // if it's a section geo trigger, // remove the section information and disable the button sectionButton.text = "N/A" sectionButton.isEnabled = false } poiGeotrigger -> { // if it's a point of interest geotrigger // find its index from the stored list val index = poiList.indexOfFirst { feature -> feature.attributes["name"] == fenceFeatureName } if (index >= 0) { // if the feature exists remove it poiList.removeAt(index) // notify the list adapter to refresh its recycler views poiListAdapter.notifyItemRemoved(index) } } } }
/** * Creates and shows a new FeatureViewFragment using the given [feature] */ private fun showFeatureViewFragment(feature: ArcGISFeature) { // stop the simulated data source stopSimulatedDataSource(false) // create a new FeatureViewFragment val featureViewFragment = FeatureViewFragment(feature) { // set its onDismissedListener to // resume the simulated data source startSimulatedDataSource(false) } // show the fragment featureViewFragment.show(supportFragmentManager, "FeatureViewFragment") }
/** * Starts the simulated data source and shows a status toast if [showAlert] is true. * The data source is resumed from its previous location if stopped before. */ private fun startSimulatedDataSource(showAlert: Boolean) = lifecycleScope.launch { // start the simulated location data source simulatedLocationDataSource.start() // recenter the map view mapView.locationDisplay.setAutoPanMode(LocationDisplayAutoPanMode.Recenter) // show a toast if true if (showAlert) { Toast.makeText(this@MainActivity, "Resumed Simulation", Toast.LENGTH_SHORT) .show() } // update the action button's drawable to a pause icon playPauseFAB.setImageResource(R.drawable.ic_baseline_pause_24) }
/** * Stops the simulated data source and shows a status toast if [showAlert] is true. */ private fun stopSimulatedDataSource(showAlert: Boolean) = lifecycleScope.launch { // stop the simulated location data source simulatedLocationDataSource.stop() // show a toast if true if (showAlert) { Toast.makeText(this@MainActivity, "Stopped Simulation", Toast.LENGTH_SHORT) .show() } // update the action button's drawable to a play icon playPauseFAB.setImageResource(R.drawable.ic_baseline_play_arrow_24) }
private fun showError(message: String) { Log.e(localClassName, message) Snackbar.make(mapView, message, Snackbar.LENGTH_SHORT).show() }}