首页 > 解决方案 > 使用 Google Maps API 时不显示“我的当前位置”按钮

问题描述

我正在尝试编写一个应用程序来搜索最近的景点,例如餐馆。我的问题是,尽管看起来编码正确,但应该将地图视图移动到当前位置的按钮没有出现。这是我的代码,摘自 onMapReady 函数:

 if (mapView != null && mapView.findViewById(Integer.parseInt("1")) != null) {
            //View locationButton = ((View) mapView.findViewById(Integer.parseInt("1")).getParent()).findViewById(Integer.parseInt("4"));
            View locationButton = ((View) mapView.findViewById(Integer.parseInt("1")).getParent()).findViewById(Integer.parseInt("2"));
            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) locationButton.getLayoutParams();
            layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
            layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
            layoutParams.setMargins(0, 0, 30, 30);
        }      

我曾尝试寻找答案,但大多数已经给出的答案都涉及仅定位而根本没有出现的问题。 Android: Google Maps API - Change position of maps toolbar 这个问题涉及到同样的问题,但是在我的应用程序中,权限是在运行时给出的,至少我认为它们是(当应用程序第一次启动时,有一个单独的活动来获取权限时间)。 我的位置按钮未显示在地图片段中

标签: javaandroidgoogle-mapsandroid-studio

解决方案


您需要在运行时请求权限 ACCESS_COARSE_LOCATION 和 ACCESS_FINE_LOCATION

@Override
public void onMapReady(GoogleMap googleMap) {
            mMap= googleMap;
            if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return;
            }
            mMap.setMyLocationEnabled(true);
            mMap.getUiSettings().setMyLocationButtonEnabled(true);

}

推荐阅读