【问题标题】:I am always getting error while using this map.setMyLocationEnabled(true); its not working使用此 map.setMyLocationEnabled(true); 时总是出错它不工作
【发布时间】:2020-01-15 10:01:53
【问题描述】:

这是我在片段中的代码

@Override
public void onMapReady(GoogleMap map) {

    map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    map.setTrafficEnabled(false);
    map.setIndoorEnabled(false);
    map.setBuildingsEnabled(false);
    map.getUiSettings().setZoomControlsEnabled(true);

         map.setMyLocationEnabled(true);
    map.getUiSettings().setMyLocationButtonEnabled(true);
    LatLng wotw = new LatLng(26.912434, 75.787270);
    map.addMarker(new MarkerOptions().position(wotw)
            .title("Walk of the Week"));
    map.moveCamera(CameraUpdateFactory.newLatLng(wotw));
    map.animateCamera(CameraUpdateFactory.zoomTo(15.0f));


}

我已经尝试了所有权限,并且我已经添加了manifest,我也收到了错误

my location requires permission ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION

请解决这个问题提前谢谢你,我会感激每一个建议

【问题讨论】:

  • 您需要为 Android M 及更高版本添加“运行时权限”。
  • 我在请求许可时完成了我正在崩溃

标签: android google-maps fragment


【解决方案1】:

在设置map.setMyLocationEnabled(true); 之前,您必须声明并检查位置权限:

首先需要在AndroidManifest.xml中声明定位权限:

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

之后,您需要在设置map.setMyLocationEnabled(true);之前检查此权限:

String MY_LOCATION_REQUEST_CODE= "LOCATION_PERMISSIONS";


@Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (ContextCompat.checkSelfPermission(this, 
        Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
           mMap.setMyLocationEnabled(true);
           } else {
                    ActivityCompat.requestPermissions(
                      new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 
                           MY_LOCATION_REQUEST_CODE);
                   }
     }

下一步您需要检查授予的权限:

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    if (requestCode == MY_LOCATION_REQUEST_CODE) {
      if (permissions.length == 1 &&
          permissions[0] == Manifest.permission.ACCESS_FINE_LOCATION &&
          grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        mMap.setMyLocationEnabled(true);
    } else {
      // Permission was denied. Display an error message.
    }
}

您可以在以下位置找到更多信息 Official documentation

【讨论】:

    猜你喜欢
    • 2016-04-09
    • 1970-01-01
    • 2014-04-26
    • 2018-07-10
    • 1970-01-01
    • 2014-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多