Get the phone's last known location using LocationManager

private double[] getGPS() {
	LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);  
	List<String> providers = lm.getProviders(true);

	/* Loop over the array backwards, and if you get an accurate location, then break out the loop*/
	Location l = null;
	
	for (int i=providers.size()-1; i>=0; i--) {
		l = lm.getLastKnownLocation(providers.get(i));
		if (l != null) break;
	}
	
	double[] gps = new double[2];
	if (l != null) {
		gps[0] = l.getLatitude();
		gps[1] = l.getLongitude();
	}
	return gps;
}

5 Comments

#
Tane Piper - April 7, 2009 at 2:29 p.m.

An improvement to this would be:

// This fetches a list of available location providers
List<String> providers = lm.getProviders(true)

This should return an array like this, depending on what is available:

['network', 'gps']

The last one will always be the most accurate, so you can then do

/* Loop over the array backwards, and if you get an accurate location, then break out the loop*/
for (int i=providers.length();i>=0;i--) {
Location l = lm.getLastKnownLocation(providers[i]);
if (l != null) break;
}

#
murphy - July 9, 2009 at 6:02 p.m.

Thanks for your comments!

I've checked the code again and updated it with your suggestions. Works perfect and quite flexible like this!

#
Donal - September 11, 2009 at 12:50 p.m.

Excellent, just what I needed.
Cheers Guys!

#
Jean-Marc - January 20, 2010 at 3:09 p.m.

This works only when I have the wireless connected and seems to never fetch info from my GPS. Any idea?

#
Gautier - March 4, 2010 at 3:58 p.m.

@Jean-Marc: Are you sure your GPS is enabled, and that you are using the ACCESS_FINE_LOCATION permission in you Manifest?

Are you using a real device or an emulator?

Add a Comment