Show device location

View on GitHubSample viewer app

Show your current position on the map, as well as switch between different types of auto pan modes.

Image of show device location

Use case

When using a map within a GIS, it may be helpful for a user to know their own location within a map, whether that's to aid the user's navigation or to provide an easy means of identifying/collecting geospatial information at their location.

How to use the sample

Tap the button in the lower right (which starts in Stop mode). A menu will appear with the following options:

  • Stop - Stops the location display.
  • On - Starts the location display with no LocationDisplayAutoPanMode mode set.
  • Re-Center - Starts the location display with LocationDisplayAutoPanMode set to Recenter.
  • Navigation - Starts the location display with LocationDisplayAutoPanMode set to Navigation.
  • Compass - Starts the location display with LocationDisplayAutoPanMode set to CompassNavigation.

How it works

  1. Create a MapView.
  2. Get the LocationDisplay.dataSource from the MapView with mapView.locationDisplay.dataSource.
  3. Use start() and stop() on the LocationDataSource as necessary.

Relevant API

  • ArcGISMap
  • LocationDisplay
  • MapView

Additional information

Location permissions are required for this sample.

This sample demonstrates the following AutoPanMode options:

  • Recenter: In this mode, the MapView attempts to keep the location symbol on-screen by re-centering the location symbol when the symbol moves outside a "wander extent". The location symbol may move freely within the wander extent, but as soon as the symbol exits the wander extent, the MapView re-centers the map on the symbol.

  • Navigation: This mode is best suited for in-vehicle navigation.

  • CompassNavigation: This mode is better suited for waypoint navigation when the user is walking.

Tags

compass, GPS, location, map, mobile, navigation

Sample Code

MainActivity.ktMainActivity.ktSpinnerAdapter.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
/* 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.
 *
 */

package com.esri.arcgismaps.sample.showdevicelocation

import android.Manifest.permission.ACCESS_COARSE_LOCATION
import android.Manifest.permission.ACCESS_FINE_LOCATION
import android.content.pm.PackageManager
import android.os.Bundle
import android.view.View
import android.widget.AdapterView
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.ApiKey
import com.arcgismaps.ArcGISEnvironment
import com.arcgismaps.location.LocationDisplayAutoPanMode
import com.arcgismaps.mapping.ArcGISMap
import com.arcgismaps.mapping.BasemapStyle
import com.esri.arcgismaps.sample.showdevicelocation.databinding.ActivityMainBinding
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)
    }

    private val mapView by lazy {
        activityMainBinding.mapView
    }

    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
        val map = ArcGISMap(BasemapStyle.ArcGISNavigationNight)
        mapView.map = map

        val locationDisplay = mapView.locationDisplay

        lifecycleScope.launch {
            // listen to changes in the status of the location data source
            locationDisplay.dataSource.start()
                .onSuccess {
                    // permission already granted, so start the location display
                    activityMainBinding.spinner.setSelection(1, true)
                }.onFailure {
                    // check permissions to see if failure may be due to lack of permissions
                    requestPermissions()
                }
            }

        // populate the list for the location display options for the spinner's adapter
        val panModeSpinnerElements = arrayListOf(
            ItemData("Stop", R.drawable.locationdisplaydisabled),
            ItemData("On", R.drawable.locationdisplayon),
            ItemData("Re-center", R.drawable.locationdisplayrecenter),
            ItemData("Navigation", R.drawable.locationdisplaynavigation),
            ItemData("Compass", R.drawable.locationdisplayheading)
        )

        activityMainBinding.spinner.apply {
            adapter = SpinnerAdapter(this@MainActivity, R.id.locationTextView, panModeSpinnerElements)
            onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
                override fun onItemSelected(
                    parent: AdapterView<*>?,
                    view: View,
                    position: Int,
                    id: Long
                ) {
                    when (panModeSpinnerElements[position].text) {
                        "Stop" ->  // stop location display
                            lifecycleScope.launch {
                                locationDisplay.dataSource.stop()
                            }
                        "On" ->  // start location display
                            lifecycleScope.launch {
                                locationDisplay.dataSource.start()
                            }
                        "Re-center" -> {
                            // re-center MapView on location
                            locationDisplay.setAutoPanMode(LocationDisplayAutoPanMode.Recenter)
                        }
                        "Navigation" -> {
                            // start navigation mode
                            locationDisplay.setAutoPanMode(LocationDisplayAutoPanMode.Navigation)
                        }
                        "Compass" -> {
                            // start compass navigation mode
                            locationDisplay.setAutoPanMode(LocationDisplayAutoPanMode.CompassNavigation)
                        }
                    }
                }

                override fun onNothingSelected(parent: AdapterView<*>?) {}
            }
        }
    }

    /**
     * Request fine and coarse location permissions for API level 23+.
     */
    private fun requestPermissions() {
        // coarse location permission
        val permissionCheckCoarseLocation =
            ContextCompat.checkSelfPermission(this@MainActivity, ACCESS_COARSE_LOCATION) ==
                    PackageManager.PERMISSION_GRANTED
        // fine location permission
        val permissionCheckFineLocation =
            ContextCompat.checkSelfPermission(this@MainActivity, ACCESS_FINE_LOCATION) ==
                    PackageManager.PERMISSION_GRANTED

        // if permissions are not already granted, request permission from the user
        if (!(permissionCheckCoarseLocation && permissionCheckFineLocation)) {
            ActivityCompat.requestPermissions(
                this@MainActivity,
                arrayOf(ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION),
                2
            )
        } else {
            // permission already granted, so start the location display
            lifecycleScope.launch {
                mapView.locationDisplay.dataSource.start().onSuccess {
                    activityMainBinding.spinner.setSelection(1, true)
                }
            }
        }
    }

    /**
     * Handle the permissions request response.
     */
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            lifecycleScope.launch {
                mapView.locationDisplay.dataSource.start().onSuccess {
                    activityMainBinding.spinner.setSelection(1, true)
                }
            }
        } else {
            Snackbar.make(
                mapView,
                "Location permissions required to run this sample!",
                Snackbar.LENGTH_LONG
            ).show()
            // update UI to reflect that the location display did not actually start
            activityMainBinding.spinner.setSelection(0, true)
        }
    }
}

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