How to Get Current Location in Googlemap Using Fusedlocationproviderclient

Unable to get current (real time) location using FusedLocationProviderClient

FusedLocationProvider can return a null Location, especially the first time it fetches a Location. So, as you have found, simply returning when the result is null will force requestLocationUpdates() to fire again and actually fetch a valid Location the second time.

I think you can also force FusedLocationProvider to have a Location the first time if you just open the Google Maps app and wait for it to obtain a GPS lock. Of course, you wouldn't want your users to have to perform this process in order for your app to work, but it's still good to know for debugging.

The cause of this seems to be that FusedLocationProvider tries to return the most recently fetched Location for the device. If this Location is too old, has never been fetched, or the user toggled on/off the Location option on their phone, it just returns null.

How to get location fast and only once using fused location provider client in 2021

     private void getUserLastLocation(FusedLocationProviderClient fusedLocationProviderClient) {

if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
Toast.makeText(getContext(), "permission deny before", Toast.LENGTH_SHORT).show();
checkSelfLoctionPermission();
}

//this logic you can write seprate to check user is enable the gps or not
//make sure before calling the location user has enabled the gps ..this
//if... else condition to help to check user has enabled gps or not

if (isLocationEnabled())//if 2
{

//u can write your logic here
}else
{
Toast.makeText(getContext(), "Please turn on" + " your location...", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);

}


//this if condition only run once.. when first time user want to take location
//this method will get fresh location (means current location)
if (!Constant.FETCHINGLOCTIONFIRSTTIEME) {
CancellationTokenSource tokenSource = new CancellationTokenSource();
CancellationToken token = tokenSource.getToken();
mFusedLocationProviderClient.
getCurrentLocation(LocationRequest.PRIORITY_HIGH_ACCURACY, token)
.addOnSuccessListener(new OnSuccessListener<Location>() {
@Override
public void onSuccess(@NonNull Location location) {

if (location != null) {

double lat=location.getLatitude();
double longt=location.getLongitude();


} else {
//don't be confused with AlertDialoBox because
//this our alerbox written by me you can write own alerbox to show the //message
Common.AlertDialogBox(getContext(), "Fetching location ",
getString(R.string.fetchingerror));


}


}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {

String message = e.getMessage();
String title = "locatuion fetching exception";
Common.AlertDialogBox(getContext(), title, message);

}
});
} else {

fusedLocationProviderClient.getLastLocation()
.addOnSuccessListener(new OnSuccessListener<Location>() {
@Override
public void onSuccess(@NonNull Location location) {
if (location != null) {
double lat=location.getLatitude();
double longt=location.getLongitude();
} else {
Toast.makeText(getContext(), "Fetching location error", Toast.LENGTH_SHORT).show();
Log.d("test", "onViewCreated" + "fetching location error");


}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
String message = e.getMessage();
String title = "locatuion fetching exception";

}
});
}//else closed
}

//to check user gps is o or not
private boolean isLocationEnabled() {
LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}

GetFusedLocationProviderClient returning null latitude and longitude values for users' location

I have faced this isue as well especially when i first install my app on a device. there are two things that you can try out that i think will help:

one is trying to open the google maps app and waiting for it to get a fix and then go on and open your app. this should provide your fused location provider client a last location that it can look up. check this answer for reference

the second is going a step further and requesting location updates using the provider. If you only need a single location fix you can then go on and deregister it once you get the first one. I am doing this for my app and usually last location is only null the first time i use the app after installation. after that it usually works. this is probably what you should do anyway as you cant expect your users to turn on google maps before using your app.

and just to be safe, be aware that fusedlocationproviderclient sometimes stops working or behaves weirdly when you have pending google services updates on your device. so go ahead and make sure your device is up to date in this regard.



Related Topics



Leave a reply



Submit