Show device location using indoor positioning

View on GitHub

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

Bring the device within range of an IPS beacon. 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 an IndoorsLocationDataSource with the positioning feature table (stored with the map) and the pathways feature table after both tables are loaded.
  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 StartAsync() and StopAsync(). Device location will appear on the display as a blue dot and update as the user moves throughout the space.
  6. Use the AutoPanMode property to change how the map behaves when location updates are received.

Relevant API

  • ArcGISFeatureTable
  • FeatureTable
  • IndoorsLocationDataSource
  • Location
  • LocationDisplay
  • LocationDisplayAutoPanMode
  • Map
  • 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

IndoorPositioning.xaml.csIndoorPositioning.xaml.csIndoorPositioning.xaml
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
// Copyright 2022 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.

using Esri.ArcGISRuntime.Data;
using Esri.ArcGISRuntime.Location;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Portal;
using Esri.ArcGISRuntime.UI;
using Microsoft.Maui.ApplicationModel;
using Location = Esri.ArcGISRuntime.Location.Location;
using Map = Esri.ArcGISRuntime.Mapping.Map;

namespace ArcGIS.Samples.IndoorPositioning
{
    [ArcGIS.Samples.Shared.Attributes.Sample(
        name: "Show device location using indoor positioning",
        category: "Location",
        description: "Show your device's real-time location while inside a building by using signals from indoor positioning beacons.",
        instructions: "Bring the device within range of an IPS beacon. 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`.",
        tags: new[] { "BLE", "Bluetooth", "GPS", "IPS", "beacon", "blue dot", "building", "facility", "indoor", "location", "map", "mobile", "navigation", "site", "transmitter" })]
    public partial class IndoorPositioning : ContentPage, IDisposable
    {
        private IndoorsLocationDataSource _indoorsLocationDataSource;

        private int? _currentFloor = null;

        // Provide your own data in order to use this sample. Code in the sample may need to be modified to work with other maps.

        #region BuildingData

        private Uri _portalUri = new Uri("https://www.arcgis.com/");

        private const string ItemId = "YOUR_ITEM_ID_HERE";

        private const string PositioningTableName = "IPS_Positioning";
        private const string PathwaysLayerName = "Pathways";

        private string[] _layerNames = new string[] { "Details", "Units", "Levels" };

        #endregion BuildingData

        public IndoorPositioning()
        {
            InitializeComponent();
            _ = Initialize();
        }

        private async Task Initialize()
        {
            try
            {
                PermissionStatus status = await Permissions.RequestAsync<Permissions.LocationWhenInUse>();
                if (status != PermissionStatus.Granted)
                {
                    throw new Exception("Location permission required for use of indoor positioning.");
                }
#if ANDROID
                // Get bluetooth permission for Android devices. AndroidBluetoothPerms is a custom PermissionStatus in this namespace.
                PermissionStatus bluetoothStatus = await Permissions.RequestAsync<AndroidBluetoothPerms>();
                if (bluetoothStatus != PermissionStatus.Granted)
                {
                    throw new Exception("Bluetooth permission is required for use of indoor positioning.");
                }
#endif
                PositioningLabel.Text = "Loading map";

                // Create a portal item for the web map.
                ArcGISPortal portal = await ArcGISPortal.CreateAsync(_portalUri, false);
                PortalItem item = await PortalItem.CreateAsync(portal, ItemId);

                // Load the map in the map view.
                MyMapView.Map = new Map(item);
                await MyMapView.Map.LoadAsync();

                PositioningLabel.Text = "Creating indoors location data source";

                // Get the positioning table from the map.
                await Task.WhenAll(MyMapView.Map.Tables.Select(table => table.LoadAsync()));
                FeatureTable positioningTable = MyMapView.Map.Tables.Single(table => table.TableName.Equals(PositioningTableName));

                // Get a table of all of the indoor pathways.
                FeatureLayer pathwaysFeatureLayer = MyMapView.Map.OperationalLayers.OfType<FeatureLayer>().Single(l => l.Name.Equals(PathwaysLayerName, StringComparison.InvariantCultureIgnoreCase));
                ArcGISFeatureTable pathwaysTable = pathwaysFeatureLayer.FeatureTable as ArcGISFeatureTable;

                // Get the global ID for positioning. The ID identifies a specific row in the feature table that should be used for setting up IPS. We use this ID to construct the data source.
                Field dateCreatedFieldName = positioningTable.Fields.Single(f => f.Name.Equals("DateCreated", StringComparison.InvariantCultureIgnoreCase) || f.Name.Equals("DATE_CREATED", StringComparison.InvariantCultureIgnoreCase));

                // Create a query for the latest created feature. This is needed for correctly constructing the IPS used in this sample. There is a constructor without an ID parameter that will attempt to automatically find the latest row.
                QueryParameters queryParameters = new QueryParameters
                {
                    MaxFeatures = 1,
                    // "1=1" will give all the features from the table.
                    WhereClause = "1=1",
                };
                queryParameters.OrderByFields.Add(new OrderBy(dateCreatedFieldName.Name, SortOrder.Descending));

                FeatureQueryResult queryResult = await positioningTable.QueryFeaturesAsync(queryParameters);
                Guid globalID = (Guid)queryResult.Single().Attributes["GlobalID"];

                // Create the indoor location data source using the tables and Guid.
                _indoorsLocationDataSource = new IndoorsLocationDataSource(positioningTable, pathwaysTable, globalID);

                PositioningLabel.Text = "Starting IPS";

                MyMapView.LocationDisplay.AutoPanMode = LocationDisplayAutoPanMode.Navigation;
                MyMapView.LocationDisplay.DataSource = _indoorsLocationDataSource;
                _indoorsLocationDataSource.LocationChanged += LocationDisplay_LocationChanged;

                await MyMapView.LocationDisplay.DataSource.StartAsync();

                PositioningLabel.Text = "Waiting for location";
            }
            catch (Exception ex)
            {
                await Application.Current.MainPage.DisplayAlert(ex.GetType().Name, ex.Message, "OK");
            }
        }

        private void LocationDisplay_LocationChanged(object sender, Location loc)
        {
            // Get the properties from the new location.
            IReadOnlyDictionary<string, object> locationProperties = loc.AdditionalSourceProperties;
            locationProperties.TryGetValue(LocationSourcePropertyKeys.Floor, out object floor);
            locationProperties.TryGetValue(LocationSourcePropertyKeys.PositionSource, out object positionSource);
            locationProperties.TryGetValue(LocationSourcePropertyKeys.SatelliteCount, out object satCount);
            locationProperties.TryGetValue("transmitterCount", out object transmitterCount);

            // Handle any floor changes.
            if (floor != null)
            {
                int newFloor = int.Parse(floor.ToString());

                // Check if the new location is on a different floor.
                if (_currentFloor == null || _currentFloor != newFloor)
                {
                    _currentFloor = newFloor;

                    // Loop through dimension layers specified for this data set.
                    foreach (DimensionLayer dimLayer in MyMapView.Map.OperationalLayers.OfType<DimensionLayer>().Where(layer => _layerNames.Contains(layer.Name)))
                    {
                        // Set the layer definition expression to only show data for the current floor.
                        dimLayer.DefinitionExpression = $"VERTICAL_ORDER = {_currentFloor}";
                    }
                }
            }

            // Create the UI label with information about the updated location.
            string labelText = string.Empty;
            if (_currentFloor != null) labelText += $"Floor: {_currentFloor}\n";
            if (positionSource != null) labelText += $"Position-source: {positionSource}\n";
            if (satCount != null) labelText += $"Satellite count: {satCount}\n";
            if (transmitterCount != null) labelText += $"Beacon count: {transmitterCount}\n";
            labelText += $"Horizontal accuracy: {string.Format("{0:0.##}", loc.HorizontalAccuracy)}m";

            // Update UI on the main thread.
            Dispatcher.Dispatch(() =>
            {
                PositioningLabel.Text = labelText;
            });
        }

        public void Dispose()
        {
            // Stop the location data source.
            _ = MyMapView.LocationDisplay?.DataSource?.StopAsync();
        }
    }

#if ANDROID

    public class AndroidBluetoothPerms : Permissions.BasePlatformPermission
    {
        public override (string androidPermission, bool isRuntime)[] RequiredPermissions
        {
            get
            {
                // Devices running Android 12 or higher need the `BluetoothScan` permission. Android 11 and below require the `Bluetooth` and `BluetoothAdmin` permissions.
                if (Android.OS.Build.VERSION.SdkInt > Android.OS.BuildVersionCodes.S)
                {
                    return new List<(string androidPermission, bool isRuntime)>
                    {
                        (global::Android.Manifest.Permission.BluetoothScan, true),
                    }.ToArray();
                }
                else
                {
                    return new List<(string androidPermission, bool isRuntime)>
                    {
                        (global::Android.Manifest.Permission.Bluetooth, true),
                        (global::Android.Manifest.Permission.BluetoothAdmin, true)
                    }.ToArray();
                }
            }
        }
    }

#endif
}

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