Show device location using indoor positioning

View on GitHubSample viewer app

Show your device's real-time location while inside a building by using signals from indoor positioning beacons.

Show device location using indoor positioning

Use case

An indoor positioning system (IPS) allows you to locate yourself and others inside a building in real time. Similar to GPS, it puts a blue dot on indoor maps and can be used with other location services to help navigate to any point of interest or destination, as well as provide an easy way to identify and collect geospatial information at their location.

How to use the sample

When the device is within range of an IPS beacon, toggle "Show Location" to change the visibility of the location indicator in the map view. The system will ask for permission to use the device's location if the user has not yet used location services in this app. It will then start the location display with auto-pan mode set to navigation.

When there is no IPS beacons nearby, or other errors occur while initializing the indoors location data source, it will seamlessly fall back to the current device location as determined by GPS.

How it works

  1. Load an IPS-enabled map. This can be a web map hosted as a portal item in ArcGIS Online, an Enterprise Portal, or a mobile map package (.mmpk) created with ArcGIS Pro.
  2. Create and load an IndoorPositioningDefinition (stored with IPS-aware maps), then create an IndoorsLocationDataSource from it.
  3. Handle location change events to respond to floor changes or read other metadata for locations.
  4. Assign the IndoorsLocationDataSource to the map view's location display.
  5. Enable and disable the map view's location display using LocationDisplay.dataSource.start() and LocationDisplay.dataSource.stop(). Device location will appear on the display as a blue dot and update as the user moves throughout the space.
  6. Use the LocationDisplay.setAutoPanMode() function to change how the map behaves when location updates are received.

Relevant API

  • ArcGISMap
  • FeatureLayer
  • FeatureTable
  • IndoorsLocationDataSource
  • LocationDataSource
  • LocationDisplay
  • MapView

About the data

This sample uses an IPS-enabled web map that displays Building L on the Esri Redlands campus. Please note: you would only be able to use the indoor positioning functionalities when you are inside this building. Swap the web map to test with your own IPS setup.

Additional information

  • Location and Bluetooth permissions are required for this sample.
  • To learn more about IPS, read the Indoor positioning article on ArcGIS Developer website.
  • To learn more about how to deploy the indoor positioning system, read the Deploy ArcGIS IPS article.

Tags

beacon, BLE, blue dot, Bluetooth, building, facility, GPS, indoor, IPS, location, map, mobile, navigation, site, transmitter

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
/* 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.showdevicelocationusingindoorpositioning

import android.Manifest
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.lifecycleScope
import com.arcgismaps.ArcGISEnvironment
import com.arcgismaps.location.IndoorPositioningDefinition
import com.arcgismaps.location.IndoorsLocationDataSource
import com.arcgismaps.location.Location
import com.arcgismaps.location.LocationDataSourceStatus
import com.arcgismaps.location.LocationDisplayAutoPanMode
import com.arcgismaps.mapping.ArcGISMap
import com.arcgismaps.mapping.PortalItem
import com.arcgismaps.mapping.layers.FeatureLayer
import com.arcgismaps.portal.Portal
import com.esri.arcgismaps.sample.showdevicelocationusingindoorpositioning.databinding.ShowDeviceLocationUsingIndoorPositioningActivityMainBinding
import com.google.android.material.snackbar.Snackbar
import kotlinx.coroutines.launch
import java.text.DecimalFormat

class MainActivity : AppCompatActivity() {

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

    private val mapView by lazy {
        activityMainBinding.mapView
    }

    private val progressBar by lazy {
        activityMainBinding.progressBar
    }

    private val textView by lazy {
        activityMainBinding.textView
    }

    // keep track of the current floor in an indoor map, null if using GPS
    private var currentFloor: Int? = null

    // provides an indoor or outdoor position based on device sensor data (radio, GPS, motion sensors).
    private var indoorsLocationDataSource: IndoorsLocationDataSource? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        lifecycle.addObserver(mapView)
        // 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
        // check for location permissions
        // if permissions is allowed, the device's current location is shown
        checkPermissions()
    }

    /**
     * Check for location permissions, if not received then request for one
     */
    private fun checkPermissions() {
        val requestCode = 1
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ||
            ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED ||
            (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S &&
                    ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED)) {
            val requestPermissions = mutableListOf(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION)
            // Android 12 required permission
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                requestPermissions.add(Manifest.permission.BLUETOOTH_SCAN)
            }
            ActivityCompat.requestPermissions(this, requestPermissions.toTypedArray(), requestCode)
        } else {
            // permission already given, so no need to request
            setUpMap()
        }
    }

    /**
     * Set up the [mapView] to load a floor-aware web map.
     */
    private fun setUpMap() {
        // load the portal and create a map from the portal item
        val portalItem = PortalItem(
            Portal("https://www.arcgis.com/"),
            "8fa941613b4b4b2b8a34ad4cdc3e4bba"
        )
        val map = ArcGISMap(portalItem)
        mapView.map = map
        lifecycleScope.launch {
            map.load().onSuccess {
                // gets indoor positioning definition from the IPS-aware map
                // and uses it to set the IndoorsLocationDataSource.
                map.indoorPositioningDefinition?.let { indoorPositioningDefinition ->
                    setupIndoorsLocationDataSource(indoorPositioningDefinition)
                } ?: showError("Map does not contain an IndoorPositioningDefinition")

            }.onFailure {
                // if map load failed, show the error
                showError("Error Loading Map: {it.message}")
            }
        }
    }

    /**
     * Sets up the [indoorsLocationDataSource] using the [indoorPositioningDefinition]
     */
    private fun setupIndoorsLocationDataSource(indoorPositioningDefinition: IndoorPositioningDefinition) {
        lifecycleScope.launch {
            indoorPositioningDefinition.load().onSuccess {
                indoorsLocationDataSource = IndoorsLocationDataSource(indoorPositioningDefinition)
                startLocationDisplay()
            }.onFailure {
                showError("Failed to load the indoorPositioningDefinition")
            }
        }
    }

    /**
     * Sets up the location listeners, the navigation mode, displays the devices location as a blue dot,
     * collect data source location changes and handles its status changes
     */
    private fun startLocationDisplay() {
        val locationDisplay = mapView.locationDisplay.apply {
            setAutoPanMode(LocationDisplayAutoPanMode.Navigation)
            dataSource = indoorsLocationDataSource
                ?: return showError("Error setting the IndoorsLocationDataSource value.")
        }

        // coroutine scope to start the location display, which will in-turn start IndoorsLocationDataSource to start receiving IPS updates.
        lifecycleScope.launch {
            locationDisplay.dataSource.start()
        }

        // coroutine scope to collect data source location changes like currentFloor, positionSource, transmitterCount, networkCount and horizontalAccuracy
        lifecycleScope.launch {
            locationDisplay.dataSource.locationChanged.collect { location ->
                // get the location properties of the LocationDataSource
                val locationProperties = location.additionalSourceProperties
                // retrieve information about the location of the device
                val floor = locationProperties["floor"]?.toString() ?: ""
                val positionSource = locationProperties["positionSource"]?.toString() ?: ""
                val transmitterCount = locationProperties["transmitterCount"]?.toString() ?: ""
                val satelliteCount = locationProperties["satelliteCount"]?.toString() ?: ""

                // check if current floor hasn't been set or if the floor has changed
                if (floor.isNotEmpty()) {
                    val newFloor = floor.toInt()
                    if (currentFloor == null || currentFloor != newFloor) {
                        currentFloor = newFloor
                        // update layer's definition express with the current floor
                        mapView.map?.operationalLayers?.forEach { layer ->
                            val name = layer.name
                            if (layer is FeatureLayer && name in listOf(
                                    "Details",
                                    "Units",
                                    "Levels"
                                )
                            ) {
                                layer.definitionExpression = "VERTICAL_ORDER = $currentFloor"
                            }
                        }
                    }
                } else {
                    showError("Floors is empty.")
                }
                // set up the message with floor properties to be displayed to the textView
                val sb = StringBuilder()
                sb.append("Floor: $floor, ")
                sb.append("Position-source: $positionSource, ")
                val accuracy = DecimalFormat(".##").format(
                    location.horizontalAccuracy
                )
                sb.append("Horizontal-accuracy: ${accuracy}m, ")
                sb.append(when (positionSource) {
                        Location.SourceProperties.Values.POSITION_SOURCE_GNSS -> "Satellite-count: $satelliteCount"
                        "BLE" -> "Transmitter-count: $transmitterCount"
                        else -> ""
                    }
                )
                textView.text = sb.toString()
            }
        }

        lifecycleScope.launch {
            // Handle status changes of IndoorsLocationDataSource
            locationDisplay.dataSource.status.collect { status ->
                when (status) {
                    LocationDataSourceStatus.Starting -> progressBar.visibility = View.VISIBLE
                    LocationDataSourceStatus.Started -> progressBar.visibility = View.GONE
                    LocationDataSourceStatus.FailedToStart -> {
                        progressBar.visibility = View.GONE
                        showError("Failed to start IndoorsLocationDataSource")
                    }
                    LocationDataSourceStatus.Stopped -> {
                        progressBar.visibility = View.GONE
                        showError("IndoorsLocationDataSource stopped due to an internal error")
                    }
                    else -> {}
                }
            }
        }
    }

    /**
     * Result of the user from location permissions request
     */
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // if location permissions accepted, start setting up IndoorsLocationDataSource
            setUpMap()
        } else {
            val message = "Location permission is not granted"
            Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
            Log.e(localClassName, message)
            progressBar.visibility = View.GONE
        }
    }

    /**
     * Displays an error onscreen
     */
    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.