Reputation: 1
I am trying to create a simple android application which have to display a map in a fragment and the last known location of the device. I would like to use Google API for the location, but whenever I call the method fusedLocationProviderClient.getLastLocation the result is always null and the position shown on the map is always latitude 0, longitude 0.
public class MapsFragment extends Fragment {
FusedLocationProviderClient client;
double latitude, longitude;
private OnMapReadyCallback callback = new OnMapReadyCallback() {
@Override
public void onMapReady(GoogleMap googleMap) {
//Check condition
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_COARSE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) {
//When permission is granted, call method
getCurrentLocation();
} else {
//When permission is not granted, request permission
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION}, 100);
}
//LatLng object creation
LatLng latLng = new LatLng(latitude, longitude);
//Set map coordinates using latLng object
googleMap.addMarker(new MarkerOptions().position(latLng).title("Current Position"));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
}
};
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater,
@Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_maps, container, false);
return v;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
SupportMapFragment mapFragment =
(SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
if (mapFragment != null) {
mapFragment.getMapAsync(callback);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//Check condition
if (requestCode == 100 && (grantResults.length > 0) && (grantResults[0] + grantResults[1] ==
PackageManager.PERMISSION_GRANTED)) {
//When permission are granted, call method
getCurrentLocation();
} else {
Toast.makeText(getActivity(), "Permission denied", Toast.LENGTH_SHORT).show();
}
}
@SuppressLint("MissingPermission")
private void getCurrentLocation() {
client = LocationServices.getFusedLocationProviderClient(getActivity());
//Initialize location manager, whose allow to get periodic updates of the location
LocationManager locationManager = (LocationManager) getActivity()
.getSystemService(Context.LOCATION_SERVICE);
//Check condition, when GPS and NETWORK provider are enabled, WORK
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
|| locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
//When location is enabled, get last location, THE PROBLEM IS THERE
client.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {
@Override
public void onComplete(@NonNull Task<Location> task) {
Location location = task.getResult();
//Check condition
if (location != null) {
//When location result is not null, set latitude and longitude
latitude = location.getLatitude();
longitude = location.getLongitude();
} else {
//When location result is not null, initialize location request
LocationRequest locationRequest = new LocationRequest()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10000)
.setFastestInterval(1000)
.setNumUpdates(1);
//Initialize location callback
LocationCallback locationCallback = new LocationCallback() {
@Override
public void onLocationResult(@NonNull LocationResult locationResult) {
//Initialize location
Location location1 = locationResult.getLastLocation();
//Set latitude and longitude
latitude = location1.getLatitude();
longitude = location1.getLatitude();
}
};
//Request location updates
client.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper());
}
}
});
} else {
//When location service is not enabled, open location setting
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
}
}
Upvotes: 0
Views: 92
Reputation: 74046
Last location is a cahced location on the device so getting null means nothing used the location recently. If you open google maps or something that uses your gps location first, let it get your location then go back into your app you will get a valid location back
Upvotes: 2