0

I use the following codes to get the location of user using FusedLocationApi however it seems that onLocationChanged really works when the location is really changed but not sends the initial location. When I start the Api nothing happens but when I change my location the target function is called.

This is how I start the Api:

   @Override
    public void onConnected(Bundle dataBundle) {
       LocationServices.FusedLocationApi.requestLocationUpdates(mLocationClient, mLocationRequest, this);
    }

And this is how I call my own function:

@Override
public void onLocationChanged(Location location) {
    if (location != null) {
        CurrentLocation=String.valueOf(location.getLatitude())+"_"+String.valueOf(location.getLongitude());
        analyzeData(CurrentLocation);
    }
}

How can I get the location as soon as onConnected is fired not on location changes. Thanks

Ali Sheikhpour
  • 10,475
  • 5
  • 41
  • 82

1 Answers1

0

onLocationChange is called only When location is changed as you said above. So if you need to get location as soon as onConnect is fired you need to get it using the blew code as a work around till onLocationChange is fired

private FusedLocationProviderClient mFusedLocationClient;

mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
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) {
                    // Logic to handle location object
                }
            }
        });
Ramzy Hassan
  • 926
  • 8
  • 21