-1

我正在使用融合位置提供程序来获取当前位置并通过它将我的标记更新到我的当前位置。我正在授予应用程序许可,然后它什么也不做。虽然我已经为此编写了代码来获取和更新地图上的位置。我之前也给出了 Access_COARSE_LOCATION,但没有任何变化。这是我的代码:-

public class MainActivity extends AppCompatActivity implements OnMapReadyCallback {

    private GoogleMap mMap;
    private FusedLocationProviderClient mFusedLocationClient;

    private static final int LOCATION_PERMISSION_REQUEST_CODE = 537;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        init();
    }

    private void init() {
    //    Initializing Objects...
        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        if (mapFragment != null) {
            mapFragment.getMapAsync(this);
        }
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
    // onMapReady check Permission and load map...
    // If Permission not granted ask for permission...
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            mMap = googleMap;
            MoveCameraToCurrentPosition();
        } else {
            AskUserPermission();
        }
    }


    public void AskUserPermission() {
        //   Show Explanation and show permission dialog...
        //   Permission is not granted
        //   Show Explanation...

        //   shouldShowRequestPermissionRationale returns true if permission has previously
        //   denied by user..

        if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
            // Show an explanation to the user *asynchronously* -- don't block
            // this thread waiting for the user's response! After the user
            // sees the explanation, try again to request the permission.
            final AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("Why we need Location Permission?");
            builder.setMessage("we want to forecast the weather alert like storms, Flood," +
                    "Hurricanes, etc. to you before hand based on your farm location, so that " +
                    "we can save your crops :).");
            builder.setNeutralButton("Got it.", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.dismiss();
                    RequestLocationPermission();
                }
            });
            builder.show();
            RequestLocationPermission();
        } else {
            //  No Explanation Needed Request Permission...
            RequestLocationPermission();
        }
    }

    // Show Alert Dialog for permission...
    private void RequestLocationPermission() {
        // No explanation needed; request the permission
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission
                .ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION},
                LOCATION_PERMISSION_REQUEST_CODE);
    }

    // Fetch Request Permission result and update current location...
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case LOCATION_PERMISSION_REQUEST_CODE:
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // This code is not executing even after giving permission..
                    MoveCameraToCurrentPosition();
                }
                break;
        }

    }
    // Move camera to current location...
    private void MoveCameraToCurrentPosition(){
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            mFusedLocationClient.getLastLocation()
                    .addOnSuccessListener(this, new OnSuccessListener<Location>() {
                        @Override
                        public void onSuccess(Location location) {
                            // Got last known location. In some rare situations this can be null.
                            if (location != null) {
                                // Add a marker in Sydney, Australia, and move the camera.
                                LatLng sydney = new LatLng(location.getLatitude(), location.getLongitude());
                                mMap.addMarker(new MarkerOptions().position(sydney).icon(BitmapDescriptorFactory.fromResource(R.drawable.barley)).title("Your Location"));
                                CameraPosition cameraPosition = new CameraPosition(sydney, 10, 0, 0);
                                CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(cameraPosition);
                                mMap.animateCamera(cameraUpdate);
                            }
                        }
                    });
        } else {
            AskUserPermission();
        }
    }
}
4

1 回答 1

0

好的,所以我的问题是在我允许位置权限后我没有调用 getMapAsync,这使我的 Google 地图对象为空,因此无法将我的相机移动到我当前的位置。我已经更新了我的代码,现在它工作正常。

public class MainActivity extends AppCompatActivity implements OnMapReadyCallback {

    private GoogleMap googleMap;
    private String TAG = this.getClass().getSimpleName();
    private FusedLocationProviderClient mFusedLocationClient;
    private SupportMapFragment mapFragment;

    private static final int LOCATION_PERMISSION_REQUEST_CODE = 537;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
        mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        if (mapFragment != null) {
            mapFragment.getMapAsync(this);
        }
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            if (googleMap != null) {
                this.googleMap = googleMap;
                MoveCameraToCurrentPosition();
            } else {
                Toast.makeText(this, "Null Object...OnMapReady", Toast.LENGTH_SHORT).show();
            }
        } else {
            AskUserPermission();
        }
    }


    public void AskUserPermission() {
        //   Show Explanation and show permission dialog...
        //   Permission is not granted
        //   Show Explanation...

        //   shouldShowRequestPermissionRationale returns true if permission has previously
        //   denied by user..

        if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
            // Show an explanation to the user *asynchronously* -- don't block
            // this thread waiting for the user's response! After the user
            // sees the explanation, try again to request the permission.
            final AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("Why we need Location Permission?");
            builder.setMessage("we want to forecast the weather alert like storms, Flood," +
                    "Hurricanes, etc. to you before hand based on your farm location, so that " +
                    "we can save your crops :).");
            builder.setNeutralButton("Got it.", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.dismiss();
                }
            });
            builder.show();
        }
        RequestLocationPermission();
    }

    private void RequestLocationPermission() {
        // No explanation needed; request the permission
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission
                        .ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION},
                LOCATION_PERMISSION_REQUEST_CODE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case LOCATION_PERMISSION_REQUEST_CODE:
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if (googleMap != null) {
                        MoveCameraToCurrentPosition();
                    } else {
                        if (mapFragment != null) {
                            mapFragment.getMapAsync(this);
                        }
                    }
                }
                break;
        }

    }

    private void MoveCameraToCurrentPosition() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            mFusedLocationClient.getLastLocation()
                    .addOnSuccessListener(this, new OnSuccessListener<Location>() {
                        @Override
                        public void onSuccess(Location location) {
                            // Got last known location. In some rare situations this can be null.
                            if (location != null) {
                                // Add a marker in Sydney, Australia, and move the camera.
                                LatLng sydney = new LatLng(location.getLatitude(), location.getLongitude());
                                googleMap.addMarker(new MarkerOptions().position(sydney).icon
                                        (BitmapDescriptorFactory.fromResource(R.drawable.barley)).title("Your Location"));
                                CameraPosition cameraPosition = new CameraPosition(sydney, 10, 0, 0);
                                CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(cameraPosition);
                                googleMap.animateCamera(cameraUpdate);
                            }
                        }
                    });
        } else {
            AskUserPermission();
        }
    }
}
于 2018-09-10T09:27:20.480 回答