Search code examples
androidgoogle-mapsgoogle-apilocation

How can I use GoogleApiClient location services with Google Api?


In a tutorial I'm watching the instructor uses GoogleApiClient for LocationServices like this.enter image description here

I know that GoogleApiClient is deprecated and we should use GoogleApi instead which incorporates all the Google Api's as per this article: https://android-developers.googleblog.com/2017/11/moving-past-googleapiclient_21.html

However, this article only talks about GoogleSignInClient and not location services at all.

My problems are as follows:

  1. I cannot find anything when I even try using GoogleSignInClient. My only dependency is this: implementation 'com.google.android.gms:play-services-location:18.0.0'

By this I mean when I type: private GoogleSignInClient googleSignInClient...nothing shows up.

  1. I can't find any GoogleApi for location services(as expected, since even GoogleSignInClient isn't showing up)

What may be going wrong here?

UPDATE:

So his code looks something like this:

private GoogleApiClient googleApiClient;
private FusedLocationProviderClient fusedLocationProviderClient;


fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(MainActivity.this);

        googleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addOnConnectionFailedListener(this)
                .addConnectionCallbacks(this)
                .build();

..but I need to translate it using GoogleApi instead of GoogleApiClient(since that's deprecated).

Thank you!


Solution

  • What you see in the video is referring to FusedLocationProviderApi deprecated API.

    If you want to use Google Play Service API to listen to the user location you need to use the new FusedLocationProviderClient, you can find the official sample implementation here

    Based on your use case, think about adding a fallback in case the device does not have Play services installed (like using the Android native API)

    Sample code using the new entrypoint class (you don't need to use the GoogleApi class directly):

    fun getLastLocationIfApiAvailable(context: Context): Task<Location>? {
        val client = LocationServices.getFusedLocationProviderClient(context)
        return GoogleApiAvailability.getInstance()
            .checkApiAvailability(client)
            .onSuccessTask { _ -> client.lastLocation }
            .addOnFailureListener { _ -> Log.d(TAG, "Location unavailable.")}
    }
    

    If you need to handle all the possible output of GoogleApiAvailability check this SO answer