Getting Location Address From Latitude And Longitude Using Google Maps Geocoding API

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

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

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 the permission from the user in the run time. Please see the code below to learn how we can get run time permissions.

  1. private boolean canAccessLocation() {  
  2.     return (hasPermission(Manifest.permission.ACCESS_FINE_LOCATION));  
  3. }  
  4. private boolean canAccessCoreLocation() {  
  5.     return (hasPermission(Manifest.permission.ACCESS_COARSE_LOCATION));  
  6. }  
  7. private boolean hasPermission(String perm) {  
  8.     return (PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(MainActivity.this, perm));  
  9. }  

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.

  1. @Override  
  2. public void onClick(View arg0) {  
  3.     if (!canAccessLocation() || !canAccessCoreLocation()) {  
  4.         requestPermissions(INITIAL_PERMS, INITIAL_REQUEST);  
  5.     } else {  
  6.         boolean networkPresent = myLocation.getLocation(MainActivity.this, MainActivity.this);  
  7.         if (!networkPresent) {  
  8.             Toast.makeText(getActivity(), ”please enable your network”, Toast.LENGTH_SHORT).show();  
  9.         }  
  10.     }  
  11. }  

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.

  1. @Override  
  2. public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {  
  3.     switch (requestCode) {  
  4.         case INITIAL_REQUEST:  
  5.             if (canAccessLocation() && canAccessCoreLocation()) {  
  6.                 boolean networkPresent = myLocation.getLocation(getActivity(), this);  
  7.                 if (!networkPresent) {  
  8.                     //TODO hanle error  
  9.                 }  
  10.             }  
  11.             break;  
  12.     }  
  13. }  

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.

  1. @Override  
  2. public void onLocationReceived(Location location) {  
  3.     double latitude = location.getLatitude();  
  4.     double longitude = location.getLongitude();  
  5. }  

Getting location address from the geo cordinates

We have got the location cordinates 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 thread like the following.

  1. public static void getAddressFromLocation(final double latitude, final double longitude, final Context context, final Handler handler) {  
  2.     Thread thread = new Thread() {  
  3.         @Override  
  4.         public void run() {  
  5.             Geocoder geocoder = new Geocoder(context, Locale.getDefault());  
  6.             String result = null;  
  7.             try {  
  8.                 List < Address > addressList = geocoder.getFromLocation(latitude, longitude, 1);  
  9.                 if (addressList != null && addressList.size() > 0) {  
  10.                     Address address = addressList.get(0);  
  11.                     StringBuilder sb = new StringBuilder();  
  12.                     for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {  
  13.                         sb.append(address.getAddressLine(i)); //.append("\n");  
  14.                     }  
  15.                     sb.append(address.getLocality()).append("\n");  
  16.                     sb.append(address.getPostalCode()).append("\n");  
  17.                     sb.append(address.getCountryName());  
  18.                     result = sb.toString();  
  19.                 }  
  20.             } catch (IOException e) {  
  21.                 Log.e("Location Address Loader""Unable connect to Geocoder", e);  
  22.             } finally {  
  23.                 Message message = Message.obtain();  
  24.                 message.setTarget(handler);  
  25.                 if (result != null) {  
  26.                     message.what = 1;  
  27.                     Bundle bundle = new Bundle();  
  28.                     bundle.putString("address", result);  
  29.                     message.setData(bundle);  
  30.                 } else {  
  31.                     message.what = 1;  
  32.                     Bundle bundle = new Bundle();  
  33.                     result = " Unable to get address for this location.";  
  34.                     bundle.putString("address", result);  
  35.                     message.setData(bundle);  
  36.                 }  
  37.                 message.sendToTarget();  
  38.             }  
  39.         }  
  40.     };  
  41.     thread.start();  
  42. }  

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.

  1. private class GeocoderHandler extends Handler {  
  2.     @Override  
  3.     public void handleMessage(Message message) {  
  4.         String locationAddress;  
  5.         switch (message.what) {  
  6.             case 1:  
  7.                 Bundle bundle = message.getData();  
  8.                 locationAddress = bundle.getString("address");  
  9.                 break;  
  10.             default:  
  11.                 locationAddress = null;  
  12.         }  
  13.         Log.e("location Address=", locationAddress);  
  14.     }  
  15. }  

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 .

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now