Search code examples
androidgoogle-mapsandroid-fragmentsmapsandroid-gps

Google Maps fragment follow blue dot


I have implemented a Google Maps fragment into my app, where the user can see their current location by clicking on the 'compass' button (in the top right corner).

This works well, however if the user moves a good distance, the blue dot will leave the map. To relocate the blue dot, the user has to press the 'compass' button again.

Is it possible to follow the blue dot, having it in the centre of the map fragment? And when the user moves, the camera is moved?

Following is the code used to show and update location on the fragment;

//Maps

@Override
public void onMapReady(GoogleMap googleMap) {

    mMap = googleMap;

    //Prompt user for permission
    getLocationPermission();

    //Setup map UI with blue dot etc
    updateLocationUI();

    // Get the current location of the device and set the position of the map.
    getDeviceLocation();
}

private void getLocationPermission() {
    if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
            android.Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {
        mLocationPermissionGranted = true;
    }
    else {
        ActivityCompat.requestPermissions(this,
                new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
                PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
    }
}

private void updateLocationUI() {
    if (mMap == null) {
        return;
    }
    try {
        if (mLocationPermissionGranted) {
            mMap.setMyLocationEnabled(true);
            mMap.getUiSettings().setMyLocationButtonEnabled(true);
        } else {
            mMap.setMyLocationEnabled(false);
            mMap.getUiSettings().setMyLocationButtonEnabled(false);

            mLastKnownLocation = null;
            getLocationPermission();
        }
    } catch (SecurityException e)  {
        Log.e("Exception: %s", e.getMessage());
    }
}

Solution

  • You need to listen to location updates, and move camera if user has moved considerable amount of distance(depends on your zoom level)

    • Bigger zoom level means, you need to move camera for small movements say few 10 meters
    • Smaller zoom level means you need to move camera less say only few 100 meters movements
    • Keep battery consumption in mind while implementing listening for location and look for best practices before implementing