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
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;
}
Thanks for your comments!
I've checked the code again and updated it with your suggestions. Works perfect and quite flexible like this!
Excellent, just what I needed.
Cheers Guys!
This works only when I have the wireless connected and seems to never fetch info from my GPS. Any idea?
@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