How do I get current location using FusedLocationProviderClient

1.9k Views Asked by At

Im trying to get device current location using FusedLocationProviderClient in a fragment. I want the user to see current device location if they accept permissions. The problem is in the getDeviceLocation() which checks whether getting location was successful or not. The logcat does not show me any errors.

Here is the java code:

public class DirectionsFragment extends Fragment implements OnMapReadyCallback  {

    GoogleMap mMap;
    Boolean mLocationPermissionGranted=false;
    public String TAG="DirectionsFragment";
    private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
    private static final String COARSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
    private static final int LOCATION_PERMISSION_CODE = 1234;
    private FusedLocationProviderClient mFusedLocationProviderClient;
    static final float DEFAULT_ZOOM = 15f;
    private Context mContext=getContext();
  OnMapReadyCallback callback=new OnMapReadyCallback() {
      @Override
      public void onMapReady(GoogleMap googleMap) {
          Toast.makeText(getContext(),"Map is Ready",Toast.LENGTH_SHORT).show();
          mMap = googleMap;
          if (mLocationPermissionGranted) {
              getDeviceLocation();
              if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

                  return;
              }

                  mMap.setMyLocationEnabled(true);
              mMap.getUiSettings().setMyLocationButtonEnabled(true);
              mMap.getUiSettings().setZoomControlsEnabled(true);
              mMap.getUiSettings().setZoomControlsEnabled(true);
          }
      }
  };

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {


        super.onViewCreated(view, savedInstanceState);
        getLocatonPermission();

    }

    private void getDeviceLocation() {

        Log.d(getTag(), "getDeviceLocation:getting device  current location");
        mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getContext());
        try {
            if (mLocationPermissionGranted=true) {

                if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    return;
                }
                Task location = mFusedLocationProviderClient.getLastLocation();
                location.addOnCompleteListener(new OnCompleteListener() {
                    @Override
                    public void onComplete(@NonNull Task task) {
                        if (task.isSuccessful()){
                            Log.d(TAG,"onComplete:found Location");
                            Location currentLocation=(Location)task.getResult();
                                moveCamera(new LatLng(currentLocation.getLatitude(),currentLocation.getLongitude()),DEFAULT_ZOOM);
                        }else{
                            Log.d(TAG,"onComplete:current location is null");
                            Toast.makeText(mContext, "unable to get current location", Toast.LENGTH_SHORT).show();

                        }
                    }
                });
            }
        }catch (SecurityException sexc){
            Log.e(TAG,"getDeviceLocation:SecurityException:"+sexc.getMessage());
        }
    }
    //What happens on map zoom
private  void moveCamera(LatLng latLng,float zoom){
Log.d(TAG,"moveCamera:moving the camera to: lat:"+latLng.latitude+","+latLng.longitude);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,zoom));
}

    public  void initMap(){
        SupportMapFragment mapFragment=(SupportMapFragment)getChildFragmentManager().findFragmentById(R.id.map);
            if (mapFragment!=null){
                mapFragment.getMapAsync(callback);
            }

    }

    private void getLocatonPermission() {

        String[] permissions={Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION
        } ;
        if (ContextCompat.checkSelfPermission(getContext(), FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {

            if (ContextCompat.checkSelfPermission(getContext(), COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                mLocationPermissionGranted = true;
                
                initMap();
            } else {
                ActivityCompat.requestPermissions(getActivity(), permissions, LOCATION_PERMISSION_CODE);
            }
        }  else {
            ActivityCompat.requestPermissions(getActivity(), permissions, LOCATION_PERMISSION_CODE);
        }
    }

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

        switch (requestCode){

            case LOCATION_PERMISSION_CODE:{
                if (grantResults.length>0){
                    for (int i=0;i<grantResults.length;++i){
                        if (grantResults[i]!=PackageManager.PERMISSION_GRANTED){
                            mLocationPermissionGranted=false;
                            return;
                        }
                    }

                    mLocationPermissionGranted=true;

                    initMap();
                }
            }
        }
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {

    }
}

XML code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <fragment
        android:id="@+id/map"
        class="com.google.android.gms.maps.MapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>
1

There are 1 best solutions below

0
On

i think you missed checking if the location provider is enabled ex:GPS so first you have to check current location provider and if the provider is disabled request the permission of customer to enable it. it is kotlin code but i think you can figure it out

LocationServices.getSettingsClient(this)
                .checkLocationSettings(LocationSettingsRequest.Builder()
                .addLocationRequest(LocationRequest().apply {
                     priority =LocationRequest.PRIORITY_HIGH_ACCURACY
                 }).build())
                .addOnSuccessListener {   
                 //  GPS is already enable, callback GPS status through listener
                 getDeviceLocation()
                }
                .addOnFailureListener { e ->
                     // ask user GPS permission
                     val rae = e as ResolvableApiException
                rae.startResolutionForResult(this,GPS_REQUEST_CODE)
                }
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    if (resultCode == Activity.RESULT_OK && requestCode == GPS_REQUEST_CODE) {
        getDeviceLocation()
    }
}