How to obtain current location with Android (Java)


Suppose in your app you would like to obtain the current location of the device. In other words, obtaining stuff like latitude, longitude, and city. Its very simple to do so with Android.

You’ll first need to import…

import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;

To obtain the latitude and longitude

LocationManager localizer = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
List<String> providers = localizer.getProviders(true);
Location bestPosition = null;
//poll for the best, most accurate location
for(String s:providers)
{
	Location temp = localizer.getLastKnownLocation(s);
	if(temp == null)
	{
		continue;
	}
	if(bestPosition == null || temp.getAccuracy() < bestPosition.getAccuracy())
	{
		bestPosition = temp;
	}
}
		
//get the lat/long
double latitude = bestPosition.getLatitude();
double longitude = bestPosition.getLongitude();

To obtain the city

Geocoder geo = new Geocoder(this, Locale.getDefault());
StringBuilder builder = new StringBuilder();
String[] finalAddress = null;
try 
{
    List
<Address> address = geo.getFromLocation(latitude, longitude, 1);
    int maxLines = address.get(0).getMaxAddressLineIndex();
    for (int i= 0; i < maxLines; i++) 
    {
	    String addressStr = address.get(0).getAddressLine(i);
	    builder.append(addressStr);
	    builder.append(" ");
    }

    finalAddress = builder.toString().split(" "); //This is the complete address.
} 
catch (IOException e) {}
catch (NullPointerException e) {}

Lastly, if you wanted to be even more specific and get just the important details of an address…

//something like so...
if (addresses.size() > 0) 
{
    System.out.println(addresses.get(0).getLocality());
    System.out.println(addresses.get(0).getCountryName());
}

This has been another quick and useful tutorial, please subscribe for new posts and tutorials. Please also rate and review, thanks! Keep coding 😉

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s