The location-data layer adds a My Location button to the top-right corner of the map. When the user taps the button the map centers on the device location. The location is shown as a blue dot if the device is stationary and as a blue chevron if the device is moving.
map.setMyLocationEnabled(Boolean) call requires permission and the code should explicitly check to see if permission is available.
Alternatively, you can suppress the missing location permission with an annotation.
You can achieve this easily by using the new Activity Result API
Here is the code
class MapsActivity : AppCompatActivity() , OnMapReadyCallback {
private lateinit var map: GoogleMap
//suppress missing permission
@SuppressLint("MissingPermission")
private val locationPermission = registerForActivityResult(ActivityResultContracts.RequestPermission()) {
isGranted ->
if (isGranted) {
//add my Location Button on top-right side corner
map.isMyLocationEnabled = true
}
else {
ActivityCompat.requestPermissions(this ,
arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION) ,
0)
}
}
The ActivityResultCallback defines how app handles the user's response to the permission request.
To display the system permissions dialog, call the launch() method on the instance of ActivityResultLauncher.
override fun onMapReady(googleMap: GoogleMap) {
map = googleMap
//call launch() passing in the permission required
locationPermission.launch(Manifest.permission.ACCESS_FINE_LOCATION)}
After launch() is called, the system permissions dialog appears. When the user makes a choice, the system asynchronously invokes implementation of ActivityResultCallback.