skip to Main Content
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

2

Answers


  1. Chosen as BEST ANSWER

    working code:

    package il.co.jonathan.monstercatch.ACTIVITIES;
    
    import android.Manifest;
    import android.content.pm.PackageManager;
    import android.location.Location;
    import android.os.Bundle;
    import android.widget.FrameLayout;
    
    import androidx.annotation.NonNull;
    import androidx.core.app.ActivityCompat;
    import androidx.fragment.app.FragmentActivity;
    
    import com.google.android.gms.location.FusedLocationProviderClient;
    import com.google.android.gms.location.LocationCallback;
    import com.google.android.gms.location.LocationResult;
    import com.google.android.gms.location.LocationServices;
    import com.google.android.gms.maps.CameraUpdateFactory;
    import com.google.android.gms.maps.GoogleMap;
    import com.google.android.gms.maps.OnMapReadyCallback;
    import com.google.android.gms.maps.SupportMapFragment;
    import com.google.android.gms.maps.model.LatLng;
    import com.google.android.gms.maps.model.MarkerOptions;
    import com.google.android.gms.tasks.OnSuccessListener;
    import com.google.android.gms.tasks.Task;
    
    import il.co.jonathan.monstercatch.R;
    
    public class Game_Activity extends FragmentActivity implements OnMapReadyCallback {
    
        private Location currentLocation;
        private LocationCallback locationCallback;
    
        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);
            locationCallback = new LocationCallback() {
                @Override
                public void onLocationResult(@NonNull LocationResult locationResult) {
                    if(locationResult == null){
                        return;
                    }
                    for (Location location : locationResult.getLocations()){
                        if(location != null){
                            currentLocation = location;
                        }
                    }
                }
            };
    
            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, 10));
                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();
                }
            }
        }
    
    }
    

    xml:

    <?xml version="1.0" encoding="utf-8"?>
    
    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
    
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        
        <fragment
            xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".ACTIVITIES.Game_Activity" />
    </RelativeLayout>
    

  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search