无法更新当前位置FusedLocationClient

问题描述 投票:-1回答: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();
        }
    }
}
android google-maps-api-3 fusedlocationproviderclient
1个回答
0
投票

好的,所以我的问题是我在允许位置许可后没有调用getMapAsync,这使得我的Google Map Object为空,因此不能将我的相机移动到我当前的位置。我已经更新了我的代码,现在它工作正常。

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();
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.