Search code examples
androidgoogle-mapsgoogle-maps-api-3google-maps-markerslocationlistener

Camera does not follow user current location in Google Maps


I have the following code with which I can display my current position when I'm starting the app.

public class MainActivity extends AppCompatActivity implements LocationListener {
   //private fields

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (isGooglePlayServicesOk()) {
            getLocationPermissions();
        }
    }

    @Override
    public void onLocationChanged(Location location) {
        this.location = location;
    //NO TOAST MESSAGE - NOTHING HAPPENS <=============
    Toast.makeText(context, location.getLatitude() + " / " + location.getLongitude(), Toast.LENGTH_SHORT).show();
    }

    //Other three empty methods onStatusChanged, onProviderEnabled and onProviderDisabled

    private void getDeviceLocation() {
        fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);

        try {
            if (locationPermissionsGranted) {
                Task task = fusedLocationProviderClient.getLastLocation();
                task.addOnCompleteListener(new OnCompleteListener() {
                    @Override
                    public void onComplete(@NonNull Task task) {
                        if (task.isSuccessful()) {
                            location = (Location) task.getResult();
                            LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
                            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 18f));
                        }
                    }
                });
            }
        } catch (SecurityException se) {
            Log.d(TAG, se.getMessage());
        }
    }

    public boolean isGooglePlayServicesOk() {
        //Method that check Google Play Services
    }

    private void initializeMap() {
        SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        supportMapFragment.getMapAsync(new OnMapReadyCallback() {
            @Override
            public void onMapReady(GoogleMap googleMap) {
                mMap = googleMap;

                if (locationPermissionsGranted) {
                    getDeviceLocation();
                    if (/* Manifest Conditions */) {return;}
                    mMap.setMyLocationEnabled(true);
                }
            }
        });
    }

    private void getLocationPermissions() {
        String[] permissions = {COARSE_LOCATION, FINE_LOCATION};
        if (ContextCompat.checkSelfPermission(this.getApplicationContext(), COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            if (ContextCompat.checkSelfPermission(this.getApplicationContext(), FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                locationPermissionsGranted = true;
                initializeMap();
            } else {
                ActivityCompat.requestPermissions(this, permissions, LOCATION_PERMISSION_REQUEST_CODE);
            }
        } else {
            ActivityCompat.requestPermissions(this, permissions, LOCATION_PERMISSION_REQUEST_CODE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        locationPermissionsGranted = false;

        switch (requestCode) {
            case LOCATION_PERMISSION_REQUEST_CODE: {
                if (grantResults.length > 0) {
                    for (int grantResult : grantResults) {
                        if (grantResult != PackageManager.PERMISSION_GRANTED) {
                            locationPermissionsGranted = false;
                            return;
                        }
                    }
                    locationPermissionsGranted = true;
                    initializeMap();
                }
            }
        }
    }
}

So everytime I'm moving, I'm not remaining centered in the map. To put me in the center of the map again, I need to press the location button. I have implemented onLocationChanged() method from the LocationListener interface but nothing happens. Not even a Toast message is displayed. How can I solve this problem, so everywhere I go, to always remain in the center of the map?

Thanks in advance!


Solution

  • As you're following this tutorial to implement the location, as mentioned at the end of it, you need to follow this one to be updated with the new location.

    Create the callback:

    mLocationCallback = new LocationCallback() {
      @Override
      public void onLocationResult(LocationResult locationResult) {
          if (locationResult == null) {
              return;
          }
          for (Location location : locationResult.getLocations()) {
              // Update UI with location data
              // ...
          }
      };
    };
    

    Set the listener/callback:

    mFusedLocationClient.requestLocationUpdates(mLocationRequest,
      mLocationCallback,
      null /* Looper */);