Android Current Location | Latitude | Longitude| Address | Country | PostalCode)

Hello Friends, today I am going to show you how we can fetch current location of user from GPS of mobile. Once we get the location of user we will have latitude and longitude from that location.

We can also use GeoCoder class to get other details like Address, Country, PostalCode from latitude and longitude.

Lets start the coding !!!

First of all we need to add permission inside Manifest.xml file for Location and Internet

 <uses-permission android:name="android.permission.INTERNET" />
 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 

Then we need to add dependency given by google for location. Here I have used version 18.0.0 but you can check the latest version here and use the latest version

implementation 'com.google.android.gms:play-services-location:18.0.0'

Next Inside your Activity or Fragment where ever you are coding create some constant and members as given below. GoogleApiClient is a class available from the play-services-location dependency.

private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private static final int REQ_CODE = 1000;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;

I have written code with Fragment so here you can see inside onViewCreated() method we can build instance mGoogleApiClient and also set a listener for connection success, connection fail,s and location as well.

If you are coding with Activity then you can write the same code inside onCreate() method.

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

        mGoogleApiClient = new GoogleApiClient.Builder(getContext())
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();

        if (mGoogleApiClient != null) {
            mGoogleApiClient.connect();
        } else
            Toast.makeText(getContext(), "Not Connected!", Toast.LENGTH_SHORT).show();
    }

Next, we need to override onStop() method and inside that method, we need to disconnect mGoogleApiClient so when we left Fragment or Activity there is no need to get location service-connected.

@Override
public void onStop() {
     mGoogleApiClient.disconnect();
     super.onStop();
}

As we have set listener with mGoogleApiClient here is a list of interfaces we need to implement with our Activity or Fragment and accordingly override methods also.

public class LocationSearchFragment extends Fragment implements GoogleApiClient.ConnectionCallbacks, LocationListener, GoogleApiClient.OnConnectionFailedListener {
    @Override
    public void onConnected(@Nullable Bundle bundle) {
    
    }
    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onLocationChanged(@NonNull Location location) {
       
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
       
    }
}

Next, we can write code inside onConnected(), which is a callback method. And it will get called when mGoogleApiClient connected successfully.

Here We are creating LocationRequest instance with interval. Once we build LocationRequest with mGoogleApiClient it will check location settings are proper or not. If all settings are proper then we can call for getLocation().

If LocationSettings required and resolution then we can request for resolution as well and to receive the result we need to override onActivityResult() method

 @Override
    public void onConnected(@Nullable Bundle bundle) {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(10000);    // 10 seconds, in milliseconds
        mLocationRequest.setFastestInterval(1000);   // 1 second, in milliseconds
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                .addLocationRequest(mLocationRequest);

        PendingResult<LocationSettingsResult> result =
                LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient,
                        builder.build());

        result.setResultCallback(new ResultCallback<LocationSettingsResult>() {

            @Override
            public void onResult(@NonNull LocationSettingsResult result) {
                final Status status = result.getStatus();
                final LocationSettingsStates state = result.getLocationSettingsStates();
                switch (status.getStatusCode()) {
                    case LocationSettingsStatusCodes.SUCCESS:
                        // All location settings are satisfied. The client can
                        // initialize location requests here.
                        getLocation();
                        break;
                    case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                        // Location settings are not satisfied, but this can be fixed
                        // by showing the user a dialog.
                        try {
                            // Show the dialog by calling startResolutionForResult(),
                            // and check the result in onActivityResult().
                            status.startResolutionForResult(getActivity(), REQ_CODE);
                        } catch (IntentSender.SendIntentException e) {
                            // Ignore the error.
                        }
                        break;
                    case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                        // Location settings are not satisfied. However, we have no way
                        // to fix the settings so we won't show the dialog.
                        break;
                }
            }

        });
    }

Here is getLocation method which we check permission first of all as android 6.0 (Marshmallow) and upper version we need to check the permissions at runtime if permission is not granted then we can not get Location Details

public void getLocation() {
        if (ActivityCompat.checkSelfPermission(getContext(), android.Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        } else {
            /*Getting the location after aquiring location service*/
            Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
                    mGoogleApiClient);

            if (mLastLocation != null) {
                //_progressBar.setVisibility(View.INVISIBLE);

                GPSTrackerNew.location=mLastLocation;
                GPSTrackerNew.latitude=mLastLocation.getLatitude();
                GPSTrackerNew.longitude=mLastLocation.getLongitude();

                getLocationDetails();

                binding.fieldLatitude.setText("Latitude: " + mLastLocation.getLatitude());
                binding.fieldLongitude.setText("Longitude: " +mLastLocation.getLongitude());
            } else {
                /*if there is no last known location. Which means the device has no data for the loction currently.
                 * So we will get the current location.
                 * For this we'll implement Location Listener and override onLocationChanged*/
                Log.i("Current Location", "No data for location found");

                if (!mGoogleApiClient.isConnected())
                    mGoogleApiClient.connect();

                LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest,this);
            }
        }
    }

Now inside the onLocationChanged() call back method we will have updated location of the user, we can also display the updated location with the help of this method.

@Override
public void onLocationChanged(@NonNull Location location) {
        double currentLatitude = location.getLatitude();
        double currentLongitude = location.getLongitude();


        GPSTrackerNew.location=location;
        GPSTrackerNew.latitude=currentLatitude;
        GPSTrackerNew.longitude=currentLongitude;

        getLocationDetails();

        binding.fieldLatitude.setText("Lat : "+currentLatitude);
        binding.fieldLongitude.setText("Long : "+currentLongitude);
}

If due to any reason connection failed then we can request for resolution with below code

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        Toast.makeText(getContext(), "Connection Failed!", Toast.LENGTH_SHORT).show();
        if (connectionResult.hasResolution()) {
            try {
                // Start an Activity that tries to resolve the error
                connectionResult.startResolutionForResult(getActivity(), CONNECTION_FAILURE_RESOLUTION_REQUEST);
            } catch (IntentSender.SendIntentException e) {
                e.printStackTrace();
            }
        } else {
            Log.i("Current Location", "Location services connection failed with code " + connectionResult.getErrorCode());
        }
    }

onActivityResult() method will help you to confirm whether the problem resolve successfully or not if problem resolve successfully then we can call for getLocation()

@Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        final LocationSettingsStates states = LocationSettingsStates.fromIntent(data);
        switch (requestCode) {
            case REQ_CODE:
                switch (resultCode) {
                    case Activity.RESULT_OK:
                        // All required changes were successfully made
                        getLocation();
                        break;
                    case Activity.RESULT_CANCELED:
                        // The user was asked to change settings, but chose not to
                        Toast.makeText(getContext(), "Location Service not Enabled", Toast.LENGTH_SHORT).show();
                        break;
                    default:
                        break;
                }
                break;
        }
    }

Here is getLocationDetails() method to display information in TextView.

Note : TextView you need to declare inside your layout file.

    private void getLocationDetails() {

        
         GPSTrackerNew gpsTracker=new GPSTrackerNew();

//            String stringLatitude = String.valueOf(gpsTracker.getLatitude());
//            binding.fieldLatitude.setText("Latitude : " + stringLatitude);
//
//            String stringLongitude = String.valueOf(gpsTracker.getLongitude());
//            binding.fieldLongitude.setText("Longitude : " + stringLongitude);

            String country = gpsTracker.getCountryName(getContext());
            binding.fieldCountry.setText("Country : " + country);

            String city = gpsTracker.getLocality(getContext());
            binding.fieldCity.setText("City : " + city);

            String postalCode = gpsTracker.getPostalCode(getContext());
            binding.fieldPostalCode.setText("PostalCode : " + postalCode);

            String addressLine = gpsTracker.getAddressLine(getContext());
            binding.fieldAddressLine.setText("Address : " + addressLine);

    }

Here is GPSTrackerNew class which will convert latitude and longitude into address, and also get Country, Postal Code as well.

public class GPSTrackerNew {

    private static final String TAG = "GPSTrackerNew";
    int geocoderMaxResults = 1;

    public static double latitude;
    public static double longitude;
    public static Location location;

    public String getCountryName(Context context) {
        List<Address> addresses = getGeocoderAddress(context);
        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String countryName = address.getCountryName();

            return countryName;
        } else {
            return null;
        }
    }

    public String getLocality(Context context) {
        List<Address> addresses = getGeocoderAddress(context);

        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String locality = address.getLocality();

            return locality;
        }
        else {
            return null;
        }
    }

    public String getPostalCode(Context context) {
        List<Address> addresses = getGeocoderAddress(context);

        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String postalCode = address.getPostalCode();

            return postalCode;
        } else {
            return null;
        }
    }

    public String getAddressLine(Context context) {
        List<Address> addresses = getGeocoderAddress(context);

        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String addressLine = address.getAddressLine(0);

            return addressLine;
        } else {
            return null;
        }
    }

    public List<Address> getGeocoderAddress(Context context) {
        if (location != null) {

            Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);

            try {
                /**
                 * Geocoder.getFromLocation - Returns an array of Addresses
                 * that are known to describe the area immediately surrounding the given latitude and longitude.
                 */
                List<Address> addresses = geocoder.getFromLocation(latitude, longitude, this.geocoderMaxResults);

                return addresses;
            } catch (IOException e) {
                //e.printStackTrace();
                Log.e(TAG, "Impossible to connect to Geocoder", e);
            }
        }

        return null;
    }
}

Thank you so much for reading this post. I hope this post helps you to improve your knowledge or solve your problem. If you have any questions please comment so I can solve your query.

Related Posts

Leave a Reply