1

This is how I enable my location button so it can be clicked on the map:

map.setMyLocationEnabled(true);

My question is, how to find this button and store it in a variable so it can be displayed or not according to the logic of my app? Thanks!

Johans Bormman
  • 855
  • 2
  • 11
  • 23

2 Answers2

1

You can get it via findViewWithTag("GoogleMapMyLocationButton") on MapFragment root view. With code like this:

public class MainActivity extends AppCompatActivity implements OnMapReadyCallback {
    ...
    private GoogleMap mGoogleMap;
    private MapFragment mMapFragment;
    private View mMyLocationButtonView = null;
    ...


    @Override
    public void onMapReady(GoogleMap googleMap) {
        mGoogleMap = googleMap;

        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int locationPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
            if (locationPermission != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String [] {Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_PERMISSION_REQUEST_CODE);
            } else {
                mGoogleMap.setMyLocationEnabled(true);
                mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
                mMyLocationButtonView = mMapFragment.getView().findViewWithTag("GoogleMapMyLocationButton");
                mMyLocationButtonView.setBackgroundColor(Color.GREEN);
            }
        }
    }
}

you'll got something like that:

MyLocationButton with custom background

Andrii Omelchenko
  • 13,183
  • 12
  • 43
  • 79
0

You can prevent the My Location button from appearing by calling UiSettings.setMyLocationButtonEnabled(false).

See https://developers.google.com/maps/documentation/android-sdk/location#my-location

Shmuel
  • 3,916
  • 2
  • 27
  • 45
  • Thanks but your solution doesn't answer my question. My question is, how to find that button and store it in a variable? – Johans Bormman Mar 18 '19 at 14:01
  • You can't do that. You can hold a reference to the GoogleMap object if you want can call googleMap.getSettings().setMyLocationButtonEnabled(false) if you want – Shmuel Mar 18 '19 at 14:02
  • 1
    The specific view is a private implementation detail of the GoogleMap object. You can get it view a findViewById, but there is no guarantee that Google won't change the view id and break your code (because its a private piece of code). Its not safe to do that. – Shmuel Mar 18 '19 at 14:03
  • How can I get it using `findViewById`? – Johans Bormman Mar 18 '19 at 14:06