Location does not update

59 views Asked by At

I have this code which gets current location with onLocationChanged. My problem is that when I move. I want it's location to change. What I get is that the app finds my current location. but it does not update the location when I'm moving. It still gets the first location. I think I have something wrong in permissions. Can you help me find the mistake in the code, so that the location will update every time that I am moving? Thank you.

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

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        checkUserLocationPermission();
    }

    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    ButtonStart = findViewById(R.id.ButtonStart);
    ButtonEnd = findViewById(R.id.ButtonEnd);

    if (count == 0) {
        ButtonEnd.setEnabled(false);
        ButtonStart.setEnabled(true);
    }

    ButtonStart.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            next_page(v);
        }
    });
    ButtonEnd.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            next_page(v);
        }
    });

    points = new ArrayList<>();
}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {

        buildGoogleApiClient();

        mMap.setMyLocationEnabled(true);
    }
}

public boolean checkUserLocationPermission() {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, Request_User_Location_Code);
        } else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, Request_User_Location_Code);
        }
        return false;
    } else {
        return true;
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestCode) {
        case Request_User_Location_Code:
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                    if (googleApiClient == null) {
                        buildGoogleApiClient();
                    }
                    mMap.setMyLocationEnabled(true);
                }
            } else {
                Toast.makeText(this, "Permission Denied...", Toast.LENGTH_SHORT).show();
            }
    }
}

protected synchronized void buildGoogleApiClient() {
    googleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();

    googleApiClient.connect();
}

@Override
public void onLocationChanged(Location location) {

    if (currentUserLocationMarker != null) {
        currentUserLocationMarker.remove();
    }

    latLng = new LatLng(location.getLatitude(), location.getLongitude());

    MarkerOptions markerOptions = new MarkerOptions();
    markerOptions.position(latLng);
    markerOptions.title("user Current Location");
    markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));

    currentUserLocationMarker = mMap.addMarker(markerOptions);

    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    mMap.animateCamera(CameraUpdateFactory.zoomBy(14));

    if (googleApiClient != null) {
        LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
    }

    points.add(latLng); //added

    redrawLine(); //added
}

@Override
public void onConnected(@Nullable Bundle bundle) {

    locationRequest = new LocationRequest();
    locationRequest.setInterval(INTERVAL);
    locationRequest.setFastestInterval(FASTEST_INTERVAL);
    locationRequest.setSmallestDisplacement(SMALLEST_DISPLACEMENT);
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
    }
}
1

There are 1 answers

0
Jignesh Jagad On

You can try like this:-

//variable
private FusedLocationProviderClient mFusedLocationClient;
private LocationRequest mLocationRequest;
private Location mCurrentLocation;
private GoogleMap mGoogleMap;

 //for current mLocation continue (declare this after declare variable)
LocationCallback mLocationCallback = new LocationCallback() {
    @Override
    public void onLocationResult(LocationResult locationResult) {
        super.onLocationResult(locationResult);
        if (locationResult.getLastLocation() != null) {
            mCurrentLocation = locationResult.getLastLocation();
            Log.d(TAG, "onLocationResult: "+mCurrentLocation);
            currentLocation();
        }
    }
};

//call after take permission of location (or in onMapReady())
//Manifest.permission.ACCESS_COARSE_LOCATION,      
//Manifest.permission.ACCESS_FINE_LOCATION
private void getlocation(){
//send request for location   add this method for get call back from time interval-->// .setInterval(2000).setFastestInterval(2000)
    mLocationRequest = new LocationRequest().setInterval(2000).setFastestInterval(2000).setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    if (ActivityCompat.checkSelfPermission(mActivity, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mActivity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    //send current location request
    mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
}