How to get current Location in GoogleMap using FusedLocationProviderClient
Asked Answered
C

5

42

I want to get periodic (say every 2 minutes) current location updates for this I'm following official documentation, I wrote this code but its not giving current location updates every two minutes even specified in LocationRequest object that I'm passing in requestLocationUpdates(), here is code:

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
    GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{

private FusedLocationProviderClient FusedLocationClient;
private GoogleApiClient mGoogleApiClient;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    if (mGoogleApiClient == null) {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }

 SupportMapFragment map = 
  getSupportFragmentManager().findFragmentById(R.id.map));

  map.getMapAsync(this);

  FusedLocationClient LocationServices.getFusedLocationProviderClient(this);
}


@Override
public void onConnected(Bundle bundle) {
    FusedLocationClient.getLastLocation()
            .addOnSuccessListener(this, new OnSuccessListener<Location>() {
                @Override
                public void onSuccess(Location location) {

                    if (location != null) {
                        Log.i("MainActivity ", "" + location.getLongitude()) 
                    }
                }
            });
FusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
FusedLocationClient.requestLocationUpdates(requestLocation(), 
new LocationCallback(){
        @Override
        public void onLocationResult(LocationResult locationResult) {
            for (Location location : locationResult.getLocations()) {
               Log.i("MainActivity ", "" + location.getLongitude());
               //not getting current location updates every 2 minutes
            }
        };

    },null);

}

@Override
public void onConnectionSuspended(int i) {}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {}
Cryptograph answered 9/7, 2017 at 0:55 Comment(0)
G
105

This is similar to my other answer here, updated to use the recently introduced FusedLocationProviderClient class.

In order to use a FusedLocationProviderClient in conjunction with a Google Map:

  1. Wait until the Google Map is ready

  2. Request the Location permission at runtime if needed

  3. Request location updates once the permission is granted

  4. Update the Google Map once the user's location is obtained

First ensure that you're using at least version 11 of Google Play Services, as older versions don't have the FusedLocationProviderClient class (newer versions will work as well):

dependencies {
      implementation 'com.google.android.gms:play-services-maps:17.0.0'
      implementation 'com.google.android.gms:play-services-location:17.0.0'
    //........
}

Note that the FusedLocationProviderClient is present in version 11.0.2, but due to bugs in the initial implementation, it's recommended that you only use this class on 11.6.0 and later. From the documentation:

Note: It's recommended to use Google Play services version 11.6.0 or higher, which includes bug fixes for this class.

Add the location permissions in the AndroidManifest.xml file, inside the manifest tag and outside of the application tag:

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

Add the API key to the AndroidManifest.xml inside the application tag:

    <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="AIza___YOUR_KEY_HERE______"/>

Kotlin

Here is the full Activity class in Kotlin:

class MapsActivity : AppCompatActivity(), OnMapReadyCallback {

    lateinit var mGoogleMap: GoogleMap
    var mapFrag: SupportMapFragment? = null
    lateinit var mLocationRequest: LocationRequest
    var mLastLocation: Location? = null
    internal var mCurrLocationMarker: Marker? = null
    internal var mFusedLocationClient: FusedLocationProviderClient? = null

    internal var mLocationCallback: LocationCallback = object : LocationCallback() {
        override fun onLocationResult(locationResult: LocationResult) {
            val locationList = locationResult.locations
            if (locationList.isNotEmpty()) {
                //The last location in the list is the newest
                val location = locationList.last()
                Log.i("MapsActivity", "Location: " + location.getLatitude() + " " + location.getLongitude())
                mLastLocation = location
                if (mCurrLocationMarker != null) {
                    mCurrLocationMarker?.remove()
                }

                //Place current location marker
                val latLng = LatLng(location.latitude, location.longitude)
                val markerOptions = MarkerOptions()
                markerOptions.position(latLng)
                markerOptions.title("Current Position")
                markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA))
                mCurrLocationMarker = mGoogleMap.addMarker(markerOptions)

                //move map camera
                mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 11.0F))
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_maps)

        supportActionBar?.title = "Map Location Activity"

        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this)

        mapFrag = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment?
        mapFrag?.getMapAsync(this)
    }

    public override fun onPause() {
        super.onPause()

        //stop location updates when Activity is no longer active
        mFusedLocationClient?.removeLocationUpdates(mLocationCallback)
    }

    override fun onMapReady(googleMap: GoogleMap) {
        mGoogleMap = googleMap
        mGoogleMap.mapType = GoogleMap.MAP_TYPE_HYBRID

        mLocationRequest = LocationRequest()
        mLocationRequest.interval = 120000 // two minute interval
        mLocationRequest.fastestInterval = 120000
        mLocationRequest.priority = LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(
                    this,
                    Manifest.permission.ACCESS_FINE_LOCATION
                ) == PackageManager.PERMISSION_GRANTED
            ) {
                //Location Permission already granted
                mFusedLocationClient?.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper())
                mGoogleMap.isMyLocationEnabled = true
            } else {
                //Request Location Permission
                checkLocationPermission()
            }
        } else {
            mFusedLocationClient?.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper())
            mGoogleMap.isMyLocationEnabled = true
        }
    }

    private fun checkLocationPermission() {
        if (ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            // Should we show an explanation?
            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.
                AlertDialog.Builder(this)
                    .setTitle("Location Permission Needed")
                    .setMessage("This app needs the Location permission, please accept to use location functionality")
                    .setPositiveButton(
                        "OK"
                    ) { _, _ ->
                        //Prompt the user once explanation has been shown
                        ActivityCompat.requestPermissions(
                            this@MapsActivity,
                            arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
                            MY_PERMISSIONS_REQUEST_LOCATION
                        )
                    }
                    .create()
                    .show()


            } else {
                // No explanation needed, we can request the permission.
                ActivityCompat.requestPermissions(
                    this,
                    arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
                    MY_PERMISSIONS_REQUEST_LOCATION
                )
            }
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>, grantResults: IntArray
    ) {
        when (requestCode) {
            MY_PERMISSIONS_REQUEST_LOCATION -> {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    // permission was granted, yay! Do the
                    // location-related task you need to do.
                    if (ContextCompat.checkSelfPermission(
                            this,
                            Manifest.permission.ACCESS_FINE_LOCATION
                        ) == PackageManager.PERMISSION_GRANTED
                    ) {

                        mFusedLocationClient?.requestLocationUpdates(
                            mLocationRequest,
                            mLocationCallback,
                            Looper.myLooper()
                        )
                        mGoogleMap.setMyLocationEnabled(true)
                    }

                } else {

                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show()
                }
                return
            }
        }// other 'case' lines to check for other
        // permissions this app might request
    }

    companion object {
        val MY_PERMISSIONS_REQUEST_LOCATION = 99
    }
}

Java

Here is the full Activity class in Java:

public class MapsActivity extends AppCompatActivity
        implements OnMapReadyCallback {

    GoogleMap mGoogleMap;
    SupportMapFragment mapFrag;
    LocationRequest mLocationRequest;
    Location mLastLocation;
    Marker mCurrLocationMarker;
    FusedLocationProviderClient mFusedLocationClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);

        getSupportActionBar().setTitle("Map Location Activity");

        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

        mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFrag.getMapAsync(this);
    }

    @Override
    public void onPause() {
        super.onPause();

        //stop location updates when Activity is no longer active
        if (mFusedLocationClient != null) {
            mFusedLocationClient.removeLocationUpdates(mLocationCallback);
        }
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mGoogleMap = googleMap;
        mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(120000); // two minute interval
        mLocationRequest.setFastestInterval(120000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);

        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED) {
                //Location Permission already granted
                mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
                mGoogleMap.setMyLocationEnabled(true);
            } else {
                //Request Location Permission
                checkLocationPermission();
            }
        }
        else {
            mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
            mGoogleMap.setMyLocationEnabled(true);
        }
    }

    LocationCallback mLocationCallback = new LocationCallback() {
        @Override
        public void onLocationResult(LocationResult locationResult) {
            List<Location> locationList = locationResult.getLocations();
            if (locationList.size() > 0) {
                //The last location in the list is the newest
                Location location = locationList.get(locationList.size() - 1);
                Log.i("MapsActivity", "Location: " + location.getLatitude() + " " + location.getLongitude());
                mLastLocation = location;
                if (mCurrLocationMarker != null) {
                    mCurrLocationMarker.remove();
                }

                //Place current location marker
                LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
                MarkerOptions markerOptions = new MarkerOptions();
                markerOptions.position(latLng);
                markerOptions.title("Current Position");
                markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
                mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);

                //move map camera
                mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 11));
            }
        }
    };

    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
    private void checkLocationPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {

            // Should we show an explanation?
            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.
                new AlertDialog.Builder(this)
                        .setTitle("Location Permission Needed")
                        .setMessage("This app needs the Location permission, please accept to use location functionality")
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                //Prompt the user once explanation has been shown
                                ActivityCompat.requestPermissions(MapsActivity.this,
                                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                                        MY_PERMISSIONS_REQUEST_LOCATION );
                            }
                        })
                        .create()
                        .show();


            } else {
                // No explanation needed, we can request the permission.
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_LOCATION );
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_LOCATION: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    // permission was granted, yay! Do the
                    // location-related task you need to do.
                    if (ContextCompat.checkSelfPermission(this,
                            Manifest.permission.ACCESS_FINE_LOCATION)
                            == PackageManager.PERMISSION_GRANTED) {

                        mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
                        mGoogleMap.setMyLocationEnabled(true);
                    }

                } else {

                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
                }
                return;
            }

            // other 'case' lines to check for other
            // permissions this app might request
        }
    }
}

activity_maps.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".map.MapsActivity">

    <fragment android:id="@+id/map"
              xmlns:tools="http://schemas.android.com/tools"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              tools:context=".map.MapsActivity"
              app:layout_constraintTop_toTopOf="parent"
              app:layout_constraintStart_toStartOf="parent"
              app:layout_constraintBottom_toBottomOf="parent"
              app:layout_constraintEnd_toEndOf="parent"
              android:name="com.google.android.gms.maps.SupportMapFragment"/>

</androidx.constraintlayout.widget.ConstraintLayout>

The user will be prompted to accept the Location permission:

enter image description here

The location will be updated on app launch, and every two minutes:

enter image description here

Extra note regarding AndroidX

If you are using AndroidX, you might need to add these lines to your gradle.properties file (see here for more info):

android.useAndroidX=true
android.enableJetifier=true
Goosestep answered 9/7, 2017 at 6:36 Comment(23)
Thanks, what about if we want to get device current location every 10 steps we move, like we are moving and getting current location update in real timeCryptograph
also there is slight change in coordinates like first i got 25.3767231 and later 25.3756256 even if device location isn't changed also after getting 2 updates the delay is increasingCryptograph
@Cryptograph For the first comment, you could set a smaller time interval, and use the setSmallestDisplacement() method on the LocationRequest: developers.google.com/android/reference/com/google/android/gms/…Goosestep
For the second comment, that sounds like normal "gps drift". It's very rare that two different location fixes would have exactly the same values, they are slightly different each time.Goosestep
What is 'mLocationCallback'? I can't find it inside variables-boxCorum
@СергейГрушин It's in the import statements: import com.google.android.gms.location.LocationCallback Also, make sure you're compiling Google Play Services location, see here: https://mcmap.net/q/169777/-placeautocompletefragment-can-39-t-resolvedGoosestep
I see we receive a collection of locations. How does that work in practice and why would be receive more than one? If we do get more than one. if you want to know your current location which one do we pick, first,last or other?Fitting
@AndrewS The explanation is here in the documentation: developers.google.com/android/reference/com/google/android/gms/… The getLocations() method says: Returns locations computed, ordered from oldest to newest.Goosestep
Do not forget to add import android.Manifest; other wise one is going to have problem with Manifest.permission.ACCESS_FINE_LOCATIONSquirearchy
FusedLocationProviderClient is not updating location when GPS is off. I couldn't find any setting to enable location updates in LocationRequest class. Is there any setting to get location updates even if the GPS is unavailable or turned off?Lailalain
@FARID Take a look here for how to prompt the user to enable the Location setting: #31236064Goosestep
When i use this code it doesn't prompt me to access device location. It just shows me the map with the default Location: 37.4219983 -122.084Monoploid
@DanielNugent What is the difference between calling requestLocationUpdates with Looper.myLooper() and null for the looper value?Arguelles
@Arguelles This is what it says in the documentation: The Looper object whose message queue will be used to implement the callback mechanism, or null to make callbacks on the calling thread. So, it looks like calling it with null is essentially the same as using Looper.myLooper().Goosestep
Don't forget to add this to manifest.xml <meta-data android:name="com.google.android.geo.API_KEY" android:value="Your Key"/>Tyranny
Shouldn't you call requestLocationUpdates in onStart ?Howitzer
@Howitzer You could do that, but then you would not be guaranteed that the map is ready by the time you get a Location, and you would have to guard against that race condition in a different way.Goosestep
@Daniel Nugent What if location callback was not called? Followed all steps but for some device OR sometimes callback was not called at all, not event last location.Lentha
In this code, the marker moves to a current location every two minutes. I want to show the current location for the very first time. So what change have to made for it?Corvus
@AnandSavjani Just call mFusedLocationClient.removeLocationUpdates(mLocationCallback); after the first location comes in.Goosestep
It actually takes sometime like 4 seconds to resolve the location.. is this expected? @DanielNugent... Also disabling and reenabling the Location services takes even 10 seconds to resolve locationnnnnnn.. is this expected?Phalangeal
@Phalangeal Getting a location lock involves a lot, including possibly communicating with multiple satellites orbiting the earth. So yes, taking 4 seconds (or sometimes longer, or sometimes not at all) is expected.Goosestep
I've placed LocationCallback mLocationCallback = new LocationCallback() in the onCreate() method. Is that why I do not receive updates in my current location?Neral
T
3

For get current location. use below code .

 if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        //Please allow Location Permission
        return;
    }
   
    FusedLocationProviderClient fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
    fusedLocationProviderClient.getCurrentLocation(PRIORITY_HIGH_ACCURACY, new CancellationToken() {
        @Override
        public boolean isCancellationRequested() {
            return false;
        }

        @NonNull
        @Override
        public CancellationToken onCanceledRequested(@NonNull OnTokenCanceledListener onTokenCanceledListener) {
            return null;
        }
    }).addOnSuccessListener(location -> {
        currentLocation = location;
        // use this current location
    });
Turtledove answered 12/1, 2022 at 14:37 Comment(0)
W
2
 mLocationCallback = new LocationCallback() {
        @Override
        public void onLocationResult(LocationResult locationResult) {
            super.onLocationResult(locationResult);
            currentLocation = locationResult.getLastLocation();

        }
    };

this work for me.

Worley answered 10/10, 2017 at 9:43 Comment(1)
What is this? Where to put it?Tragacanth
R
-1
    private LocationRequest locationRequest;

    public class MapsActivity extends FragmentActivity implements LocationListener{

    locationRequest = new LocationRequest();
    locationRequest.setInterval(60 * 1000);
    locationRequest.setFastestInterval(15 * 1000);
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);


@Override
public void onLocationChanged(Location location) {

    latitude = location.getLatitude();
    longitude = location.getLongitude();

}

Implement Location change listener and you will be able to override onlocation changed...

Retroaction answered 9/7, 2017 at 1:32 Comment(0)
P
-2

For make it simple, try with this library https://github.com/mrmans0n/smart-location-lib. This will use the Fused Location Provider.

You just put this code

SmartLocation.with(context).location(new LocationBasedOnActivityProvider(callback))
    .start(new OnLocationUpdatedListener() { ... });
Persist answered 9/3, 2018 at 4:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.