Display device location

Learn how to display the current device location on a map or scene.

display device location

You can display the device location on a map or scene. This is important for workflows that require the user's current location, such as finding nearby businesses, navigating from the current location, or identifying and collecting geospatial information.

By default, location display uses the device's location provider. Your app can also process input from other location providers, such as an external GPS receiver or a provider that returns a simulated location. For more information, see the Show device location topic.

Prerequisites

The following are required for this tutorial:

  1. An ArcGIS account to access API keys. If you don't have an account, sign up for free.
  2. Confirm that your system meets the system requirements.
  3. An IDE for Android development in Kotlin.

Steps

Open an Android Studio project

  1. To start this tutorial, complete the Display a map tutorial. Or download and unzip the Display a map solution in a new folder.

  2. Modify the old project for use in this new tutorial. Expand More info for instructions.

    1. On your file system, delete the .idea folder, if present, at the top level of your project.

    2. In the Android tool window, open app > res > values > strings.xml.

      In the <string name="app_name"> element, change the text content to Display device location.

      strings.xml
             
      Change line
      1
      2
      3
      4
      5
      6
      7
      <resources>
      
          <string name="app_name">Display device location</string>
      
          <string name="location_permission_denied">LocationDisplayManager cannot run because location permission was denied</string>
      
      </resources>
    3. In the Android tool window, open Gradle Scripts > settings.gradle.

      Change the value of rootProject.name to "Display device location".

      settings.gradle
         
      Change line
      1
      2
      3
      include ':app'
      
      rootProject.name = "Display device location"
    4. Click File > Sync Project with Gradle files. Android Studio will recognize your changes and create a new .idea folder.

  3. If you downloaded the Display a map solution project, get your API key and set it in your app.

    An API Key enables access to services, web maps, and web scenes hosted in ArcGIS Online.

    1. Go to your developer dashboard to get your API key. For these tutorials, use your default API key. It is scoped to include all of the services demonstrated in the tutorials.

    2. In Android Studio: in the Android tool window, open app > java > com.example.app > MainActivity.

    3. In the setApiKeyForApp() method, find the ArcGISRuntimeEnvironment.setApiKey("YOUR_API_KEY") call and paste your API key inside the quotes, replacing YOUR_API_KEY.

      MainActivity.kt
                                                                                               
      Change line
      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
      /*
       * Copyright 2020 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
       *
       *    https://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.example.app
      
      import android.os.Bundle
      import androidx.appcompat.app.AppCompatActivity
      
      import com.esri.arcgisruntime.ArcGISRuntimeEnvironment
      import com.esri.arcgisruntime.mapping.ArcGISMap
      import com.esri.arcgisruntime.mapping.BasemapStyle
      import com.esri.arcgisruntime.mapping.Viewpoint
      import com.esri.arcgisruntime.mapping.view.MapView
      
      import com.example.app.databinding.ActivityMainBinding
      
      class MainActivity : AppCompatActivity() {
      
          private val activityMainBinding by lazy {
            ActivityMainBinding.inflate(layoutInflater)
          }
      
          private val mapView: MapView by lazy {
            activityMainBinding.mapView
          }
      
          override fun onCreate(savedInstanceState: Bundle?) {
              super.onCreate(savedInstanceState)
      
              setContentView(activityMainBinding.root)
      
              setApiKeyForApp()
      
              setupMap()
      
          }
      
          override fun onPause() {
              mapView.pause()
              super.onPause()
          }
      
          override fun onResume() {
              super.onResume()
              mapView.resume()
          }
      
          override fun onDestroy() {
              mapView.dispose()
              super.onDestroy()
          }
      
          private fun setApiKeyForApp(){
              // set your API key
              // Note: it is not best practice to store API keys in source code. The API key is referenced
              // here for the convenience of this tutorial.
      
              ArcGISRuntimeEnvironment.setApiKey("YOUR_API_KEY")
      
          }
      
          // set up your map here. You will call this method from onCreate()
          private fun setupMap() {
      
              // create a map with the BasemapStyle streets
              val map = ArcGISMap(BasemapStyle.ARCGIS_TOPOGRAPHIC)
      
              // set the map to be displayed in the layout's MapView
              mapView.map = map
      
              // set the viewpoint, Viewpoint(latitude, longitude, scale)
              mapView.setViewpoint(Viewpoint(34.0270, -118.8050, 72000.0))
      
          }
      
      }
      

Add import statements

  1. Replace app-specific import statements with the imports (highlighted in yellow) needed for this tutorial.

    MainActivity.kt
    16 16 16 16 16 16 16 16 16 16 16 16 16 16 16 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38
    Change lineChange lineChange lineChange lineChange lineChange lineChange lineChange lineChange lineChange lineChange line
    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
    /*
     * Copyright 2020 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
     *
     *    https://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.example.app
    
    import android.os.Bundle
    import androidx.appcompat.app.AppCompatActivity
    
    
    import android.content.pm.PackageManager
    import android.Manifest
    import android.widget.Toast
    import androidx.core.app.ActivityCompat
    import androidx.core.content.ContextCompat
    
    import com.esri.arcgisruntime.ArcGISRuntimeEnvironment
    import com.esri.arcgisruntime.mapping.ArcGISMap
    import com.esri.arcgisruntime.mapping.BasemapStyle
    import com.esri.arcgisruntime.mapping.view.MapView
    import com.esri.arcgisruntime.mapping.view.LocationDisplay
    
    import com.example.app.databinding.ActivityMainBinding
    
    
    class MainActivity : AppCompatActivity() {
    
        private val activityMainBinding by lazy {
            ActivityMainBinding.inflate(layoutInflater)
        }
    
        private val mapView: MapView by lazy {
            activityMainBinding.mapView
        }
    
        private val locationDisplay: LocationDisplay by lazy { mapView.locationDisplay }
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
    
            setContentView(activityMainBinding.root)
    
            setApiKeyForApp()
    
            setupMap()
    
        }
    
        override fun onPause() {
            mapView.pause()
            super.onPause()
        }
    
        override fun onResume() {
            super.onResume()
            mapView.resume()
        }
    
        override fun onDestroy() {
            mapView.dispose()
            super.onDestroy()
        }
    
        private fun setApiKeyForApp(){
            // set your API key
            // Note: it is not best practice to store API keys in source code. The API key is referenced
            // here for the convenience of this tutorial.
    
            ArcGISRuntimeEnvironment.setApiKey("YOUR_API_KEY")
    
        }
    
        // set up your map here. You will call this method from onCreate()
        private fun setupMap() {
            // create a map with the BasemapStyle Topographic
            val map = ArcGISMap(BasemapStyle.ARCGIS_TOPOGRAPHIC)
    
            // set the map to be displayed in the layout's MapView
            mapView.map = map
    
            locationDisplay.addDataSourceStatusChangedListener {
                // if LocationDisplay isn't started or has an error
                if (!it.isStarted && it.error != null) {
                    // check permissions to see if failure may be due to lack of permissions
                    requestPermissions(it)
                }
            }
    
            locationDisplay.setAutoPanMode(LocationDisplay.AutoPanMode.RECENTER)
            locationDisplay.startAsync()
    
        }
    
        private fun requestPermissions(dataSourceStatusChangedEvent: LocationDisplay.DataSourceStatusChangedEvent) {
            val requestCode = 2
            val reqPermissions = arrayOf(
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION
            )
            // fine location permission
            val permissionCheckFineLocation =
                ContextCompat.checkSelfPermission(this@MainActivity, reqPermissions[0]) ==
                        PackageManager.PERMISSION_GRANTED
            // coarse location permission
            val permissionCheckCoarseLocation =
                ContextCompat.checkSelfPermission(this@MainActivity, reqPermissions[1]) ==
                        PackageManager.PERMISSION_GRANTED
            if (!(permissionCheckFineLocation && permissionCheckCoarseLocation)) { // if permissions are not already granted, request permission from the user
                ActivityCompat.requestPermissions(this@MainActivity, reqPermissions, requestCode)
            } else {
                // report other unknown failure types to the user - for example, location services may not
                // be enabled on the device.
                val message = String.format(
                    "Error in DataSourceStatusChangedListener: %s", dataSourceStatusChangedEvent
                        .source.locationDataSource.error.message
                )
                Toast.makeText(this@MainActivity, message, Toast.LENGTH_LONG).show()
            }
        }
    
        override fun onRequestPermissionsResult(
            requestCode: Int,
            permissions: Array<String>,
            grantResults: IntArray
        ) {
            // if request is cancelled, the results array is empty
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                locationDisplay.startAsync()
            }
    
            else {
                Toast.makeText(
                    this@MainActivity,
                    resources.getString(R.string.location_permission_denied),
                    Toast.LENGTH_SHORT
                ).show()
            }
    
        }
    
    }
    

Ask user for permission to display location

Set the user permissions to allow display location.

  1. In Android.Manifest.xml, add permissions for coarse and fine location.

    MainActivity.kt
    6 6 6 6 6 6 7 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8
    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
    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.example.app">
    
        <uses-permission android:name="android.permission.INTERNET" />
    
        <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    
        <uses-feature
            android:glEsVersion="0x00020000"
            android:required="true" />
    
        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
            <activity android:name="com.example.app.MainActivity">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
        </application>
    
    </manifest>
  2. In MainActivity.kt, create the requestPermissions() method.

    Check whether your app already has permissions for accessing fine location and coarse location by calling checkSelfPermission(). If one or both permissions have not been granted, then request permission from the user by calling ActivityCompat.requestPermissions(). Otherwise, show a Toast with a non-permission error, if any, retrieved from the status changed event that is passed to the current method.

    MainActivity.kt
    105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 104 103 102 101 100 99 98 97 96 95 94 94 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 120 119 118 117 116 115 114 113 112 111 110 109 108 107 106 105 104 103 102 101 100 100
    Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.
    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
    /*
     * Copyright 2020 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
     *
     *    https://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.example.app
    
    import android.os.Bundle
    import androidx.appcompat.app.AppCompatActivity
    
    
    import android.content.pm.PackageManager
    import android.Manifest
    import android.widget.Toast
    import androidx.core.app.ActivityCompat
    import androidx.core.content.ContextCompat
    
    import com.esri.arcgisruntime.ArcGISRuntimeEnvironment
    import com.esri.arcgisruntime.mapping.ArcGISMap
    import com.esri.arcgisruntime.mapping.BasemapStyle
    import com.esri.arcgisruntime.mapping.view.MapView
    import com.esri.arcgisruntime.mapping.view.LocationDisplay
    
    import com.example.app.databinding.ActivityMainBinding
    
    
    class MainActivity : AppCompatActivity() {
    
        private val activityMainBinding by lazy {
            ActivityMainBinding.inflate(layoutInflater)
        }
    
        private val mapView: MapView by lazy {
            activityMainBinding.mapView
        }
    
        private val locationDisplay: LocationDisplay by lazy { mapView.locationDisplay }
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
    
            setContentView(activityMainBinding.root)
    
            setApiKeyForApp()
    
            setupMap()
    
        }
    
        override fun onPause() {
            mapView.pause()
            super.onPause()
        }
    
        override fun onResume() {
            super.onResume()
            mapView.resume()
        }
    
        override fun onDestroy() {
            mapView.dispose()
            super.onDestroy()
        }
    
        private fun setApiKeyForApp(){
            // set your API key
            // Note: it is not best practice to store API keys in source code. The API key is referenced
            // here for the convenience of this tutorial.
    
            ArcGISRuntimeEnvironment.setApiKey("YOUR_API_KEY")
    
        }
    
        // set up your map here. You will call this method from onCreate()
        private fun setupMap() {
            // create a map with the BasemapStyle Topographic
            val map = ArcGISMap(BasemapStyle.ARCGIS_TOPOGRAPHIC)
    
            // set the map to be displayed in the layout's MapView
            mapView.map = map
    
            locationDisplay.addDataSourceStatusChangedListener {
                // if LocationDisplay isn't started or has an error
                if (!it.isStarted && it.error != null) {
                    // check permissions to see if failure may be due to lack of permissions
                    requestPermissions(it)
                }
            }
    
            locationDisplay.setAutoPanMode(LocationDisplay.AutoPanMode.RECENTER)
            locationDisplay.startAsync()
    
        }
    
        private fun requestPermissions(dataSourceStatusChangedEvent: LocationDisplay.DataSourceStatusChangedEvent) {
            val requestCode = 2
            val reqPermissions = arrayOf(
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION
            )
            // fine location permission
            val permissionCheckFineLocation =
                ContextCompat.checkSelfPermission(this@MainActivity, reqPermissions[0]) ==
                        PackageManager.PERMISSION_GRANTED
            // coarse location permission
            val permissionCheckCoarseLocation =
                ContextCompat.checkSelfPermission(this@MainActivity, reqPermissions[1]) ==
                        PackageManager.PERMISSION_GRANTED
            if (!(permissionCheckFineLocation && permissionCheckCoarseLocation)) { // if permissions are not already granted, request permission from the user
                ActivityCompat.requestPermissions(this@MainActivity, reqPermissions, requestCode)
            } else {
                // report other unknown failure types to the user - for example, location services may not
                // be enabled on the device.
                val message = String.format(
                    "Error in DataSourceStatusChangedListener: %s", dataSourceStatusChangedEvent
                        .source.locationDataSource.error.message
                )
                Toast.makeText(this@MainActivity, message, Toast.LENGTH_LONG).show()
            }
        }
    
        override fun onRequestPermissionsResult(
            requestCode: Int,
            permissions: Array<String>,
            grantResults: IntArray
        ) {
            // if request is cancelled, the results array is empty
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                locationDisplay.startAsync()
            }
    
            else {
                Toast.makeText(
                    this@MainActivity,
                    resources.getString(R.string.location_permission_denied),
                    Toast.LENGTH_SHORT
                ).show()
            }
    
        }
    
    }
    
  3. Override the onRequestPermissionsResult() callback inherited from the FragmentActivity class.

    If the grant results array indicates that location permissions were granted, then start the location display. (In this tutorial, we test only the first permission in the array, which is for fine location.)

    When the locationDisplay.startAsync() call in setupMap() fails to start the location display, the status of the data source changes, causing the status change listener's lambda to be executed. (You will edit setupMap() and add the data source status change listener in the next section of this tutorial: Show the current location.)

    The lambda calls this app's requestPermissions() method, which ultimately results in onRequestPermissionsResult() being called. At this point, you verified location permissions, so it's time for another attempt to start location display.

    MainActivity.kt
    132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 131 130 129 128 127 126 125 124 123 122 121 121 121 121 121 121 121 121 121 121 121 121 121 121 121 121 121 121 121 121 121 121 121 121 121 121 121 121 121 121 122 123 124 125 126 127 128 129 130 131 131 131 131 131 131 131 131 131 132 132 132
    Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.
    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
    /*
     * Copyright 2020 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
     *
     *    https://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.example.app
    
    import android.os.Bundle
    import androidx.appcompat.app.AppCompatActivity
    
    
    import android.content.pm.PackageManager
    import android.Manifest
    import android.widget.Toast
    import androidx.core.app.ActivityCompat
    import androidx.core.content.ContextCompat
    
    import com.esri.arcgisruntime.ArcGISRuntimeEnvironment
    import com.esri.arcgisruntime.mapping.ArcGISMap
    import com.esri.arcgisruntime.mapping.BasemapStyle
    import com.esri.arcgisruntime.mapping.view.MapView
    import com.esri.arcgisruntime.mapping.view.LocationDisplay
    
    import com.example.app.databinding.ActivityMainBinding
    
    
    class MainActivity : AppCompatActivity() {
    
        private val activityMainBinding by lazy {
            ActivityMainBinding.inflate(layoutInflater)
        }
    
        private val mapView: MapView by lazy {
            activityMainBinding.mapView
        }
    
        private val locationDisplay: LocationDisplay by lazy { mapView.locationDisplay }
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
    
            setContentView(activityMainBinding.root)
    
            setApiKeyForApp()
    
            setupMap()
    
        }
    
        override fun onPause() {
            mapView.pause()
            super.onPause()
        }
    
        override fun onResume() {
            super.onResume()
            mapView.resume()
        }
    
        override fun onDestroy() {
            mapView.dispose()
            super.onDestroy()
        }
    
        private fun setApiKeyForApp(){
            // set your API key
            // Note: it is not best practice to store API keys in source code. The API key is referenced
            // here for the convenience of this tutorial.
    
            ArcGISRuntimeEnvironment.setApiKey("YOUR_API_KEY")
    
        }
    
        // set up your map here. You will call this method from onCreate()
        private fun setupMap() {
            // create a map with the BasemapStyle Topographic
            val map = ArcGISMap(BasemapStyle.ARCGIS_TOPOGRAPHIC)
    
            // set the map to be displayed in the layout's MapView
            mapView.map = map
    
            locationDisplay.addDataSourceStatusChangedListener {
                // if LocationDisplay isn't started or has an error
                if (!it.isStarted && it.error != null) {
                    // check permissions to see if failure may be due to lack of permissions
                    requestPermissions(it)
                }
            }
    
            locationDisplay.setAutoPanMode(LocationDisplay.AutoPanMode.RECENTER)
            locationDisplay.startAsync()
    
        }
    
        private fun requestPermissions(dataSourceStatusChangedEvent: LocationDisplay.DataSourceStatusChangedEvent) {
            val requestCode = 2
            val reqPermissions = arrayOf(
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION
            )
            // fine location permission
            val permissionCheckFineLocation =
                ContextCompat.checkSelfPermission(this@MainActivity, reqPermissions[0]) ==
                        PackageManager.PERMISSION_GRANTED
            // coarse location permission
            val permissionCheckCoarseLocation =
                ContextCompat.checkSelfPermission(this@MainActivity, reqPermissions[1]) ==
                        PackageManager.PERMISSION_GRANTED
            if (!(permissionCheckFineLocation && permissionCheckCoarseLocation)) { // if permissions are not already granted, request permission from the user
                ActivityCompat.requestPermissions(this@MainActivity, reqPermissions, requestCode)
            } else {
                // report other unknown failure types to the user - for example, location services may not
                // be enabled on the device.
                val message = String.format(
                    "Error in DataSourceStatusChangedListener: %s", dataSourceStatusChangedEvent
                        .source.locationDataSource.error.message
                )
                Toast.makeText(this@MainActivity, message, Toast.LENGTH_LONG).show()
            }
        }
    
        override fun onRequestPermissionsResult(
            requestCode: Int,
            permissions: Array<String>,
            grantResults: IntArray
        ) {
            // if request is cancelled, the results array is empty
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                locationDisplay.startAsync()
            }
    
            else {
                Toast.makeText(
                    this@MainActivity,
                    resources.getString(R.string.location_permission_denied),
                    Toast.LENGTH_SHORT
                ).show()
            }
    
        }
    
    }
    
  4. If location permissions were not granted, show a Toast saying that permissions were denied.

    MainActivity.kt
    132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 132 131 130 129 128 127 126 125 124 123 122 121 121 121 121 121 121 121 121 121 121 121 121 121 121 121 121 121 121 121 121 121 121 121 121 121 121 121 121 121 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 140 140
    Add line.Add line.Add line.Add line.Add line.Add line.Add line.
    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
    /*
     * Copyright 2020 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
     *
     *    https://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.example.app
    
    import android.os.Bundle
    import androidx.appcompat.app.AppCompatActivity
    
    
    import android.content.pm.PackageManager
    import android.Manifest
    import android.widget.Toast
    import androidx.core.app.ActivityCompat
    import androidx.core.content.ContextCompat
    
    import com.esri.arcgisruntime.ArcGISRuntimeEnvironment
    import com.esri.arcgisruntime.mapping.ArcGISMap
    import com.esri.arcgisruntime.mapping.BasemapStyle
    import com.esri.arcgisruntime.mapping.view.MapView
    import com.esri.arcgisruntime.mapping.view.LocationDisplay
    
    import com.example.app.databinding.ActivityMainBinding
    
    
    class MainActivity : AppCompatActivity() {
    
        private val activityMainBinding by lazy {
            ActivityMainBinding.inflate(layoutInflater)
        }
    
        private val mapView: MapView by lazy {
            activityMainBinding.mapView
        }
    
        private val locationDisplay: LocationDisplay by lazy { mapView.locationDisplay }
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
    
            setContentView(activityMainBinding.root)
    
            setApiKeyForApp()
    
            setupMap()
    
        }
    
        override fun onPause() {
            mapView.pause()
            super.onPause()
        }
    
        override fun onResume() {
            super.onResume()
            mapView.resume()
        }
    
        override fun onDestroy() {
            mapView.dispose()
            super.onDestroy()
        }
    
        private fun setApiKeyForApp(){
            // set your API key
            // Note: it is not best practice to store API keys in source code. The API key is referenced
            // here for the convenience of this tutorial.
    
            ArcGISRuntimeEnvironment.setApiKey("YOUR_API_KEY")
    
        }
    
        // set up your map here. You will call this method from onCreate()
        private fun setupMap() {
            // create a map with the BasemapStyle Topographic
            val map = ArcGISMap(BasemapStyle.ARCGIS_TOPOGRAPHIC)
    
            // set the map to be displayed in the layout's MapView
            mapView.map = map
    
            locationDisplay.addDataSourceStatusChangedListener {
                // if LocationDisplay isn't started or has an error
                if (!it.isStarted && it.error != null) {
                    // check permissions to see if failure may be due to lack of permissions
                    requestPermissions(it)
                }
            }
    
            locationDisplay.setAutoPanMode(LocationDisplay.AutoPanMode.RECENTER)
            locationDisplay.startAsync()
    
        }
    
        private fun requestPermissions(dataSourceStatusChangedEvent: LocationDisplay.DataSourceStatusChangedEvent) {
            val requestCode = 2
            val reqPermissions = arrayOf(
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION
            )
            // fine location permission
            val permissionCheckFineLocation =
                ContextCompat.checkSelfPermission(this@MainActivity, reqPermissions[0]) ==
                        PackageManager.PERMISSION_GRANTED
            // coarse location permission
            val permissionCheckCoarseLocation =
                ContextCompat.checkSelfPermission(this@MainActivity, reqPermissions[1]) ==
                        PackageManager.PERMISSION_GRANTED
            if (!(permissionCheckFineLocation && permissionCheckCoarseLocation)) { // if permissions are not already granted, request permission from the user
                ActivityCompat.requestPermissions(this@MainActivity, reqPermissions, requestCode)
            } else {
                // report other unknown failure types to the user - for example, location services may not
                // be enabled on the device.
                val message = String.format(
                    "Error in DataSourceStatusChangedListener: %s", dataSourceStatusChangedEvent
                        .source.locationDataSource.error.message
                )
                Toast.makeText(this@MainActivity, message, Toast.LENGTH_LONG).show()
            }
        }
    
        override fun onRequestPermissionsResult(
            requestCode: Int,
            permissions: Array<String>,
            grantResults: IntArray
        ) {
            // if request is cancelled, the results array is empty
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                locationDisplay.startAsync()
            }
    
            else {
                Toast.makeText(
                    this@MainActivity,
                    resources.getString(R.string.location_permission_denied),
                    Toast.LENGTH_SHORT
                ).show()
            }
    
        }
    
    }
    

Show the current location

Each map view has its own instance of a LocationDisplay for showing the current location (point) of the device. The location is displayed as an overlay in the map view.

Instances of this class manage the display of device location on a map view: the symbols, animation, auto pan behavior, and so on. Location display is an overlay of the map view, and displays above everything else, including graphics overlays.

The location display does not retrieve location information, that is the job of the associated data source, which provides location updates on a regular basis. In addition to the default system location data source, you can use location providers based on external GPS devices or a simulated location source.

Each map view has its own instance of a location display and instances of location display and location data source are not shared by multiple map views. This allows you to start and stop location display independently on multiple map views without affecting each other.

  1. In setupMap, delete the code that sets the map's initial viewpoint.

    MainActivity.kt
                                                                                             
    Remove lineRemove line
    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
    /*
     * Copyright 2020 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
     *
     *    https://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.example.app
    
    import android.os.Bundle
    import androidx.appcompat.app.AppCompatActivity
    
    import com.esri.arcgisruntime.ArcGISRuntimeEnvironment
    import com.esri.arcgisruntime.mapping.ArcGISMap
    import com.esri.arcgisruntime.mapping.BasemapStyle
    import com.esri.arcgisruntime.mapping.Viewpoint
    import com.esri.arcgisruntime.mapping.view.MapView
    
    import com.example.app.databinding.ActivityMainBinding
    
    class MainActivity : AppCompatActivity() {
    
        private val activityMainBinding by lazy {
          ActivityMainBinding.inflate(layoutInflater)
        }
    
        private val mapView: MapView by lazy {
          activityMainBinding.mapView
        }
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
    
            setContentView(activityMainBinding.root)
    
            setApiKeyForApp()
    
            setupMap()
    
        }
    
        override fun onPause() {
            mapView.pause()
            super.onPause()
        }
    
        override fun onResume() {
            super.onResume()
            mapView.resume()
        }
    
        override fun onDestroy() {
            mapView.dispose()
            super.onDestroy()
        }
    
        private fun setApiKeyForApp(){
            // set your API key
            // Note: it is not best practice to store API keys in source code. The API key is referenced
            // here for the convenience of this tutorial.
    
            ArcGISRuntimeEnvironment.setApiKey("YOUR_API_KEY")
    
        }
    
        // set up your map here. You will call this method from onCreate()
        private fun setupMap() {
    
            // create a map with the BasemapStyle streets
            val map = ArcGISMap(BasemapStyle.ARCGIS_TOPOGRAPHIC)
    
            // set the map to be displayed in the layout's MapView
            mapView.map = map
    
            // set the viewpoint, Viewpoint(latitude, longitude, scale)
            mapView.setViewpoint(Viewpoint(34.0270, -118.8050, 72000.0))
    
        }
    
    }
    
  2. In setupMap(), add a listener that detects when the status of the location data source changes. In the listener's lambda, call the request permissions method so the user can approve location permissions.

    MainActivity.kt
    84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 100 100 100 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101
    Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.
    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
    /*
     * Copyright 2020 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
     *
     *    https://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.example.app
    
    import android.os.Bundle
    import androidx.appcompat.app.AppCompatActivity
    
    
    import android.content.pm.PackageManager
    import android.Manifest
    import android.widget.Toast
    import androidx.core.app.ActivityCompat
    import androidx.core.content.ContextCompat
    
    import com.esri.arcgisruntime.ArcGISRuntimeEnvironment
    import com.esri.arcgisruntime.mapping.ArcGISMap
    import com.esri.arcgisruntime.mapping.BasemapStyle
    import com.esri.arcgisruntime.mapping.view.MapView
    import com.esri.arcgisruntime.mapping.view.LocationDisplay
    
    import com.example.app.databinding.ActivityMainBinding
    
    
    class MainActivity : AppCompatActivity() {
    
        private val activityMainBinding by lazy {
            ActivityMainBinding.inflate(layoutInflater)
        }
    
        private val mapView: MapView by lazy {
            activityMainBinding.mapView
        }
    
        private val locationDisplay: LocationDisplay by lazy { mapView.locationDisplay }
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
    
            setContentView(activityMainBinding.root)
    
            setApiKeyForApp()
    
            setupMap()
    
        }
    
        override fun onPause() {
            mapView.pause()
            super.onPause()
        }
    
        override fun onResume() {
            super.onResume()
            mapView.resume()
        }
    
        override fun onDestroy() {
            mapView.dispose()
            super.onDestroy()
        }
    
        private fun setApiKeyForApp(){
            // set your API key
            // Note: it is not best practice to store API keys in source code. The API key is referenced
            // here for the convenience of this tutorial.
    
            ArcGISRuntimeEnvironment.setApiKey("YOUR_API_KEY")
    
        }
    
        // set up your map here. You will call this method from onCreate()
        private fun setupMap() {
            // create a map with the BasemapStyle Topographic
            val map = ArcGISMap(BasemapStyle.ARCGIS_TOPOGRAPHIC)
    
            // set the map to be displayed in the layout's MapView
            mapView.map = map
    
            locationDisplay.addDataSourceStatusChangedListener {
                // if LocationDisplay isn't started or has an error
                if (!it.isStarted && it.error != null) {
                    // check permissions to see if failure may be due to lack of permissions
                    requestPermissions(it)
                }
            }
    
            locationDisplay.setAutoPanMode(LocationDisplay.AutoPanMode.RECENTER)
            locationDisplay.startAsync()
    
        }
    
        private fun requestPermissions(dataSourceStatusChangedEvent: LocationDisplay.DataSourceStatusChangedEvent) {
            val requestCode = 2
            val reqPermissions = arrayOf(
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION
            )
            // fine location permission
            val permissionCheckFineLocation =
                ContextCompat.checkSelfPermission(this@MainActivity, reqPermissions[0]) ==
                        PackageManager.PERMISSION_GRANTED
            // coarse location permission
            val permissionCheckCoarseLocation =
                ContextCompat.checkSelfPermission(this@MainActivity, reqPermissions[1]) ==
                        PackageManager.PERMISSION_GRANTED
            if (!(permissionCheckFineLocation && permissionCheckCoarseLocation)) { // if permissions are not already granted, request permission from the user
                ActivityCompat.requestPermissions(this@MainActivity, reqPermissions, requestCode)
            } else {
                // report other unknown failure types to the user - for example, location services may not
                // be enabled on the device.
                val message = String.format(
                    "Error in DataSourceStatusChangedListener: %s", dataSourceStatusChangedEvent
                        .source.locationDataSource.error.message
                )
                Toast.makeText(this@MainActivity, message, Toast.LENGTH_LONG).show()
            }
        }
    
        override fun onRequestPermissionsResult(
            requestCode: Int,
            permissions: Array<String>,
            grantResults: IntArray
        ) {
            // if request is cancelled, the results array is empty
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                locationDisplay.startAsync()
            }
    
            else {
                Toast.makeText(
                    this@MainActivity,
                    resources.getString(R.string.location_permission_denied),
                    Toast.LENGTH_SHORT
                ).show()
            }
    
        }
    
    }
    
  3. Set a LocationDisplay.AutoPanMode that centers the map at the device location. Then try to start the location display.

    MainActivity.kt
    84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 104 104 104 104 104 104 104 104 104 104 104 104 104 104 104 104 104 104 104 104 104 104 104 104 104 104 104 104 104 104 104 104 104 104 104 104 104 104 104 104 104 104 104 104 104 104 104 104 104
    Add line.Add line.
    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
    /*
     * Copyright 2020 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
     *
     *    https://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.example.app
    
    import android.os.Bundle
    import androidx.appcompat.app.AppCompatActivity
    
    
    import android.content.pm.PackageManager
    import android.Manifest
    import android.widget.Toast
    import androidx.core.app.ActivityCompat
    import androidx.core.content.ContextCompat
    
    import com.esri.arcgisruntime.ArcGISRuntimeEnvironment
    import com.esri.arcgisruntime.mapping.ArcGISMap
    import com.esri.arcgisruntime.mapping.BasemapStyle
    import com.esri.arcgisruntime.mapping.view.MapView
    import com.esri.arcgisruntime.mapping.view.LocationDisplay
    
    import com.example.app.databinding.ActivityMainBinding
    
    
    class MainActivity : AppCompatActivity() {
    
        private val activityMainBinding by lazy {
            ActivityMainBinding.inflate(layoutInflater)
        }
    
        private val mapView: MapView by lazy {
            activityMainBinding.mapView
        }
    
        private val locationDisplay: LocationDisplay by lazy { mapView.locationDisplay }
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
    
            setContentView(activityMainBinding.root)
    
            setApiKeyForApp()
    
            setupMap()
    
        }
    
        override fun onPause() {
            mapView.pause()
            super.onPause()
        }
    
        override fun onResume() {
            super.onResume()
            mapView.resume()
        }
    
        override fun onDestroy() {
            mapView.dispose()
            super.onDestroy()
        }
    
        private fun setApiKeyForApp(){
            // set your API key
            // Note: it is not best practice to store API keys in source code. The API key is referenced
            // here for the convenience of this tutorial.
    
            ArcGISRuntimeEnvironment.setApiKey("YOUR_API_KEY")
    
        }
    
        // set up your map here. You will call this method from onCreate()
        private fun setupMap() {
            // create a map with the BasemapStyle Topographic
            val map = ArcGISMap(BasemapStyle.ARCGIS_TOPOGRAPHIC)
    
            // set the map to be displayed in the layout's MapView
            mapView.map = map
    
            locationDisplay.addDataSourceStatusChangedListener {
                // if LocationDisplay isn't started or has an error
                if (!it.isStarted && it.error != null) {
                    // check permissions to see if failure may be due to lack of permissions
                    requestPermissions(it)
                }
            }
    
            locationDisplay.setAutoPanMode(LocationDisplay.AutoPanMode.RECENTER)
            locationDisplay.startAsync()
    
        }
    
        private fun requestPermissions(dataSourceStatusChangedEvent: LocationDisplay.DataSourceStatusChangedEvent) {
            val requestCode = 2
            val reqPermissions = arrayOf(
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION
            )
            // fine location permission
            val permissionCheckFineLocation =
                ContextCompat.checkSelfPermission(this@MainActivity, reqPermissions[0]) ==
                        PackageManager.PERMISSION_GRANTED
            // coarse location permission
            val permissionCheckCoarseLocation =
                ContextCompat.checkSelfPermission(this@MainActivity, reqPermissions[1]) ==
                        PackageManager.PERMISSION_GRANTED
            if (!(permissionCheckFineLocation && permissionCheckCoarseLocation)) { // if permissions are not already granted, request permission from the user
                ActivityCompat.requestPermissions(this@MainActivity, reqPermissions, requestCode)
            } else {
                // report other unknown failure types to the user - for example, location services may not
                // be enabled on the device.
                val message = String.format(
                    "Error in DataSourceStatusChangedListener: %s", dataSourceStatusChangedEvent
                        .source.locationDataSource.error.message
                )
                Toast.makeText(this@MainActivity, message, Toast.LENGTH_LONG).show()
            }
        }
    
        override fun onRequestPermissionsResult(
            requestCode: Int,
            permissions: Array<String>,
            grantResults: IntArray
        ) {
            // if request is cancelled, the results array is empty
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                locationDisplay.startAsync()
            }
    
            else {
                Toast.makeText(
                    this@MainActivity,
                    resources.getString(R.string.location_permission_denied),
                    Toast.LENGTH_SHORT
                ).show()
            }
    
        }
    
    }
    

Run your app

  1. Click Run > Run > app to run the app.

    The Android Emulator should display and run your app in the Android Virtual Devcie (AVD) selected in the Android Studio toolbar:

    Currently selected AVD in Android Studio

    If your app builds but no AVD displays, you need to add one. Click Tools > AVD Manager > Create Virtual Device...

    You should see your current location displayed on the map. Different location symbols are used depending on the auto pan mode and whether a location is acquired. See LocationDisplay.AutoPanMode for details.

    By default, a round blue symbol is used to display the device's location. The location data source tries to get the most accurate location available but depending upon signal strength, satellite positions, and other factors, the location reported could be an approximation. A semi-transparent circle around the location symbol indicates the range of accuracy. As the device moves and location updates are received, the location symbol will be repositioned on the map.

What's next?

Learn how to use additional API features, ArcGIS platform services, and ArcGIS tools in these tutorials:

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