如何在 Google 地图 Android 上找到 MyLocationButton?

How find MyLocationButton on Google maps Android?

这就是我启用位置按钮以便可以在地图上单击它的方式:

map.setMyLocationEnabled(true);

我的问题是,如何找到这个按钮并将其存储在一个变量中,以便根据我的应用程序的逻辑显示或不显示?谢谢!

您可以通过调用 UiSettings.setMyLocationButtonEnabled(false) 来防止“我的位置”按钮出现。

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

您可以通过 MapFragment 根视图上的 findViewWithTag("GoogleMapMyLocationButton") 获取它。使用这样的代码:

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);
            }
        }
    }
}

你会得到类似的东西: