Tuesday, September 21, 2021

How to get current location in android ?

 

Android location API’s are highly metamorphotic.

From their humble beginnings using locationManager widget, today there are a range of options including google fused location, locationServices, GPSwidgets, and NetworkWidgets.

But, as of September 2021, the best stands out to be Geocoder widget. I really found it simple, easy to implement and quit straight-forward, unlike other libraries.


| Geocoder does not use GPS or Networks. It uses Maps Services to reverse geocode information.


 Through this code sample, you will get to call the android device location coordinates and also the street name, location details and pincode.


The example assumes that you have already created an xml layout resource file with textView of EditText placeholders for latitude and longitude. Let us assume the editText android:id for both placeholders as et_lat and et_lon, respectively. Also have a button, that can handle eventListeners, for getting location with android:id btn_getlocation.

 In this code I have implemented View.OnClickListener. However, you can replace this geocoder code within your .setOnClickListener, too.

 Now, here is the Java  code:


public class Your_Activity extends AppCompatActivity implements
       
View.OnClickListener  {

   
private static final int REQUEST_LOCATION = 1;
    FusedLocationProviderClient
fusedLocationProviderClient;


   
@Override
   
protected void onCreate(Bundle savedInstanceState) {
       
super.onCreate(savedInstanceState);
        setContentView(R.layout.
youractivity);
        ActivityCompat.requestPermissions(
this,
               
new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);


       
//Enter Location
      
btn_location = (Button) findViewById(R.id.btn_location);

       btn_location.setOnClickListener(this);


       
et_lat = (EditText) findViewById(R.id.location);
       
et_lon = (EditText) findViewById(R.id.address);

       
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(Your_Activity.this);

    }

   
@RequiresApi(api = Build.VERSION_CODES.M)
   
@Override
   
public void onClick(View view) {
if (view == btn_location) {


if (ActivityCompat.checkSelfPermission(Contribute_BO.this, Manifest.permission.ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED) {
    showLocation();
}
else{
 ActivityCompat.requestPermissions(Your_Activity.
this, new String [] {Manifest.permission.ACCESS_FINE_LOCATION},REQUEST_LOCATION);
            }
    }
    }

   
private void showLocation() {
       
fusedLocationProviderClient.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {
           
@Override
           
public void onComplete(@NonNull Task<Location> task) {
                Location location = task.getResult();
               
if (location != null){
                    Geocoder geocoder =
new Geocoder(Your_Activity.this, Locale.getDefault());
                   
try {
                        List<Address> addressList = geocoder.getFromLocation(location.getLatitude(),location.getLongitude(),
1);
                       
et_location.setText("Lat: "+addressList.get(0).getLatitude());
                       
et_address.setText("Lon: "+addressList.get(0).getLongitude());
                    } 
catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }
}

You can further drill down the Location details like:

Street Name = addresses.get(0).getAddressLine(0);

City Name = addressList.get(0).getLocality() ;

State Name = addressList.get(0).getAdminArea();

Country Name = addressList.get(0). getCountryName ();
Postal Code = addressList.get(0). getPostalCode();

 

To know more about Geocoder API refer the official documentation here.


At the moment, as of 2021, there are no usage limits for this Geocoder API. However, as with any other android widget, the Google's Geocoder API could be subject to change! So, try to use Android Studio's Location API's with discretion. 


No comments: