无法更新当前位置FusedLocationClient

时间:2018-09-10 08:28:52

标签: android google-maps-api-3 fusedlocationproviderclient

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

ntile

1 个答案:

答案 0 :(得分:0)

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

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();
        }
    }
}