How can I request location permission when clicking on the MyLocation button?

858 views Asked by At

I want to request location permission when the user clicks on the MyLocation button.

I followed this tutorial but they have requested location permission when the activity starts. But I want to request permission when clicking on the MyLocation button.

I searched on the whole internet to find anyone who has faced the same problem but I did not find anything.

This command googleMap.setMyLocationEnabled(true); does not work without grant location permission.

MyLocation button is an optional feature and not required inside my app.

Is it possible to do something like that or I should find another solution?

1

There are 1 answers

4
Rohit Kumar On

Remove the enableMyLocation() function call from onMapReady() callback, and call it in onMyLocationButtonClick(). Like mentioned below:

@Override
public void onMapReady(GoogleMap googleMap) {
    map = googleMap;
    map.setOnMyLocationButtonClickListener(this);
    map.setOnMyLocationClickListener(this);
}

And then

@Override
public boolean onMyLocationButtonClick() {
    enableMyLocation();
    Toast.makeText(this, "MyLocation button clicked", Toast.LENGTH_SHORT).show();
    // Return false so that we don't consume the event and the default behavior still occurs
    // (the camera animates to the user's current position).
    return false;
}