如何在Google Maps Android上找到MyLocationButton?

时间:2019-03-18 13:52:23

标签: android google-maps google-maps-api-3 location-button

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

map.setMyLocationEnabled(true);

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

2 个答案:

答案 0 :(得分:1)

您可以通过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);
            }
        }
    }
}

您会得到类似的东西:

MyLocationButton with custom background

答案 1 :(得分:0)

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

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