Unable to get location using LocationRequest or getLastLocation()

739 views Asked by At

I've been working on this for quite some time. I've tried everything I can think of.

I'm trying to get a rough location (Coarse location). First try was the following:

googleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this, 0 /* clientId */, this)
            .addApi(Places.GEO_DATA_API)
            .addApi(LocationServices.API)
            .build();

googleApiClient.connect();

And then this:

@Override
public void onConnected(Bundle bundle)
{
    lastKnownLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);

    if(lastKnownLocation == null)
    {
        LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
    }
    else
    {
        moveMap();
    }
}

This returns null. Totally possible, no worries. However, after this, I tried to request location updates using LocationRequest, as follows:

locationRequest = new LocationRequest();
    locationRequest.setInterval(10000);
    locationRequest.setFastestInterval(5000);
    locationRequest.setPriority(LocationRequest.PRIORITY_LOW_POWER);

And then this:

@Override
public void onLocationChanged(Location location)
{
    lastKnownLocation = location;
    LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
    moveMap();
}

Both of these methods don't give me any sort of a location. That's possible as well, so I downloaded a Fake GPS app, set Location Mode to GPS Only in phone settings, and set a fake location.

When I run my app after doing this, it still fails to find a location. I've also tried with:

locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY)
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)

Nothing seems to work. Permissions are in the manifest. What am I doing wrong?

2

There are 2 answers

0
Asim On BEST ANSWER

Fixed it by doing the following:

Removed this:

googleApiClient = new GoogleApiClient.Builder(this)
        .enableAutoManage(this, 0 /* clientId */, this)
        .addApi(Places.GEO_DATA_API)
        .addApi(LocationServices.API)
        .build();

googleApiClient.connect();

Added this:

googleApiClient = new GoogleApiClient.Builder(this)
        .enableAutoManage(this, 0 /* clientId */, this)
        .addConnectionCallbacks(this)
        .addApi(Places.GEO_DATA_API)
        .addApi(LocationServices.API)
        .build();

And moved the connect() call to onStart().

I assume the problem was the absence of addConnectionCallbacks.

2
Kirankumar Zinzuvadia On

Have you done this to start getting location updates ?

LocationServices.FusedLocationApi.requestLocationUpdates( 
            mGoogleApiClient, mLocationRequest, this);

Please check this answer.