public class Game_Activity extends FragmentActivity implements OnMapReadyCallback {
private Location currentLocation;
private FusedLocationProviderClient fusedClient;
private static final int REQUEST_CODE =101;
private FrameLayout map;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
map=findViewById(R.id.map);
fusedClient = LocationServices.getFusedLocationProviderClient(this);
getLocation();
}
private void getLocation() {
if (ActivityCompat.checkSelfPermission(
this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(
this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
REQUEST_CODE);
return;
}
Task<Location> task = fusedClient.getLastLocation();
task.addOnSuccessListener(new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if (location != null) {
currentLocation = location;
SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
assert supportMapFragment != null;
supportMapFragment.getMapAsync(Game_Activity.this);
}
}
});
}
@Override
public void onMapReady(GoogleMap googleMap) {
googleMap.getUiSettings().setScrollGesturesEnabled(false);
LatLng latLng = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
MarkerOptions markerOptions = new MarkerOptions().position(latLng).title("Player");
googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
googleMap.addMarker(markerOptions);
}
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,@NonNull int[] grantResults){
super.onRequestPermissionsResult(requestCode,permissions,grantResults);
if(requestCode == REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getLocation();
}
}
}
}
this is my code I am trying to make a map on for it to zoom it to my current location when i start it (like in pokemon go) and it doesnt zoom in.I tried to debug and the location in the on success method seems to stay null anyone got any fix?
A fix for the problem
You might be receiving a null current Location on success callback. Look on this Location Callback documentation to get the lastest location. You can use ViewModel to update the coordinate and then use that coordinate to zoom on the map.