Это приложение должно отображать текущее местоположение пользователя на карте. Я использую класс FusedLocationProviderClient
, чтобы выполнить эту работу, получая текущее известное местоположение пользователя и отображая его пользователю через тост и на карте.
Приложение работает, но моя проблема в том, что после запуска приложения карта не отображается, только тост
MainActivity Code:
FusedLocationProviderClient fusedLocationProviderClient;
private static int REQUEST_CODE = 101;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(MainActivity.this) ;
fetchLastLocation();
}
private void fetchLastLocation() {
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},REQUEST_CODE);
return;
}
Task<Location> task = fusedLocationProviderClient.getLastLocation();
task.addOnSuccessListener(new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if(location!=null)
currentLocation = location;
Toast.makeText(getApplicationContext(),currentLocation.getLatitude()+ "" + currentLocation.getLongitude(),Toast.LENGTH_SHORT).show();
SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.google_map);
assert supportMapFragment!=null;
supportMapFragment.getMapAsync(MainActivity.this);
}
});
}
@Override
public void onMapReady(GoogleMap googleMap) {
LatLng latLng = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
googleMap.addMarker(new MarkerOptions().position(latLng).title("I am here"));
googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,15));
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
fetchLastLocation();
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
} ```