简体   繁体   中英

Can't get user location using Google's LocationServices API

I am trying to get the location from the user but when I put the following request code for the location:

private void getLocation() {
    mLastLocation = LocationServices.FusedLocationApi
            .getLastLocation(mGoogleApiClient);

    if (mLastLocation != null) {
        double latitude = mLastLocation.getLatitude();
        double longitude = mLastLocation.getLongitude();
    }
}

It crashes because it gets the mLastLocation null

I call the function in the onResume() method but with no success. But if I put it in a button click callback, it gets the location.

Is there any way to get the location once the application has loaded?

First you should check that you have the required permissions to make this request.

You should get user location after you are connected to Google's LocationServices API.

Then you should request location asynchronously using Task returned by FusedLocationProviderClient.getLastLocation()

Here is some code to help you out:

GoogleApiClient mGoogleApiClient;

private void getGoogleApiClient() {
    if (mGoogleApiClient == null) {
        mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
                .addApi(LocationServices.API)
                .addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
                    @Override
                    public void onConnected(@Nullable Bundle bundle) {
                        FusedLocationProviderClient mFusedLocationClient = LocationServices.getFusedLocationProviderClient(getActivity());

                        if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                            Log.e(getClass().getName(), "Location permission not granted");
                            return;
                        }

                        Task task = mFusedLocationClient.getLastLocation();

                        task.addOnSuccessListener(getActivity(), new OnSuccessListener<Location>() {
                            @Override
                            public void onSuccess(Location location) {
                                // Got last known location. In some rare situations this can be null.
                                if (location != null) {
                                    double latitude = location.getLatitude();
                                    double longitude = location.getLongitude();
                                }
                            }
                        });
                    }

                    @Override
                    public void onConnectionSuspended(int i) {
                        Log.e(getClass().getName(), "onConnectionSuspended() ");
                    }
                })
                .addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
                    @Override
                    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
                        Log.e(getClass().getName(), "Get location failure : " + connectionResult.getErrorMessage());
                    }
                })
                .build();
    }
    mGoogleApiClient.connect();
}

Simply call the method getGoogleApiClient() when you need location. Do make sure GPS location is activated on your device.

For more infos on this topic:

https://developer.android.com/training/location/retrieve-current.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM