Introduction
This article demonstrates how to get the location address from latitude and longitude. This article will also describe how to get the current latitude and longitude in Android. This article starts with fetching the current geo-location in Android. We will get the current location address using Google Maps Geocoding API.
Defining permissions in Android
- <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
- <uses-permission android:name="android.permission.INTERNET" />
For accessing the location service, we need to first give the above permissions in the AndroidManifest.xml file. With this permission only, we will get the latitude and longitude. From the Marshmallow operating system onwards, we don't need to give permission in the Manifest file, we just get permission from the user in the run time. Please see the code below to learn how we can get run time permissions.
- private boolean canAccessLocation() {
- return (hasPermission(Manifest.permission.ACCESS_FINE_LOCATION));
- }
- private boolean canAccessCoreLocation() {
- return (hasPermission(Manifest.permission.ACCESS_COARSE_LOCATION));
- }
- private boolean hasPermission(String perm) {
- return (PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(MainActivity.this, perm));
- }
On the button click, we need to check the permission. If permission is granted, then we need to fetch the location, otherwise we need to ask for permission.
- @Override
- public void onClick(View arg0) {
- if (!canAccessLocation() || !canAccessCoreLocation()) {
- requestPermissions(INITIAL_PERMS, INITIAL_REQUEST);
- } else {
- boolean networkPresent = myLocation.getLocation(MainActivity.this, MainActivity.this);
- if (!networkPresent) {
- Toast.makeText(getActivity(), ”please enable your network”, Toast.LENGTH_SHORT).show();
- }
- }
- }
If the user has not given any permission, it will ask for the permission from the user for accessing location. And, there will be one callback event for this - like onActivityResult. That is onRequestPermissionResult().
Please see the code below.
- @Override
- public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
- switch (requestCode) {
- case INITIAL_REQUEST:
- if (canAccessLocation() && canAccessCoreLocation()) {
- boolean networkPresent = myLocation.getLocation(getActivity(), this);
- if (!networkPresent) {
-
- }
- }
- break;
- }
- }
This will be exactly like onActivityResult and here, you can check the request code. If the permission is granted, then perform the desired operation else show warning message to the user.
In the MyLocation.java class, the system will be checking the network or the GPS to get the location coordinates and there will be one Callback for this. And in the Activity or Fragment which implement this interface, we will get the location in this callback method.
- @Override
- public void onLocationReceived(Location location) {
- double latitude = location.getLatitude();
- double longitude = location.getLongitude();
- }
Getting location address from the geo-coordinates
We have got the location coordinates in the onLocationReceived callback of the Activity/Fragment. Now, we need to get the location address from these latitude and longitude coordinates. For this, we need to create a threadlike the following.
- public static void getAddressFromLocation(final double latitude, final double longitude, final Context context, final Handler handler) {
- Thread thread = new Thread() {
- @Override
- public void run() {
- Geocoder geocoder = new Geocoder(context, Locale.getDefault());
- String result = null;
- try {
- List < Address > addressList = geocoder.getFromLocation(latitude, longitude, 1);
- if (addressList != null && addressList.size() > 0) {
- Address address = addressList.get(0);
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
- sb.append(address.getAddressLine(i));
- }
- sb.append(address.getLocality()).append("\n");
- sb.append(address.getPostalCode()).append("\n");
- sb.append(address.getCountryName());
- result = sb.toString();
- }
- } catch (IOException e) {
- Log.e("Location Address Loader", "Unable connect to Geocoder", e);
- } finally {
- Message message = Message.obtain();
- message.setTarget(handler);
- if (result != null) {
- message.what = 1;
- Bundle bundle = new Bundle();
- bundle.putString("address", result);
- message.setData(bundle);
- } else {
- message.what = 1;
- Bundle bundle = new Bundle();
- result = " Unable to get address for this location.";
- bundle.putString("address", result);
- message.setData(bundle);
- }
- message.sendToTarget();
- }
- }
- };
- thread.start();
- }
We need to call the above method from onLocationReceived callback. The above method is a handler thread and it will return the result into a Handler, so we need to create a handler class to retrieve the result, like the following.
- private class GeocoderHandler extends Handler {
- @Override
- public void handleMessage(Message message) {
- String locationAddress;
- switch (message.what) {
- case 1:
- Bundle bundle = message.getData();
- locationAddress = bundle.getString("address");
- break;
- default:
- locationAddress = null;
- }
- Log.e("location Address=", locationAddress);
- }
- }
Summary
In this article, I have discussed how to get the current geo-location in Android. We also saw how we can get the location address from latitude and longitude.