albatross
albatross

Reputation: 455

Android get Location doesnt work properly

Im trying to get location and the code works but it does not work properly. Here is my code

    // Get the location manager
    LocationManager locationManager = (LocationManager)                 
    getSystemService(LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    String bestProvider = locationManager.getBestProvider(criteria, false);
    Location location = locationManager.getLastKnownLocation(bestProvider);

    try {
        lat =  (int)Math.round((location.getLatitude () * 1e6) ) ;
        lon =   (int)Math.round((location.getLongitude() * 1e6) ) ;
    }
    catch (NullPointerException e){
        lat = -1;
        lon = -1;
    }

the problem is when Im using foursqure or facebook they get the location directly but my application returns -1,-1 (sometimes) and sometimes it finds the location accurately. What might be the problem or how can I improve to get the current location better ?? Thanks

Upvotes: 0

Views: 423

Answers (2)

Stochastically
Stochastically

Reputation: 7846

The call to getLastKnownLocation sometimes returns null, as specified in the Andorid documentation. So sometimes that code will indeed produce lat=lon=-1. Also, getBestProvider is a way of determining the provider that best satisfies given criteria. Since you're not specifying any criteria, the logical conclusion is that all providers are equally good, so the result may be random. Finally, note that lat=-1 and lon=-1 is a valid location, so in general it's not a good way of flagging an error.

As suggested in another answer here, you should implement http://developer.android.com/reference/android/location/LocationListener.html . You then have the problem of which providers to use. My approach is to use them all and use a simple Kalman Filter to take care of the fact that different providers at different times have different levels of accuracy. I posted the simple kalman filter that I use for this here Smooth GPS data

Upvotes: 0

Hoan Nguyen
Hoan Nguyen

Reputation: 18151

You should implements a LocationListerner and request location update. Once you get a fix you can remove the location update. You can read more info at http://developer.android.com/reference/android/location/LocationListener.html

Upvotes: 1

Related Questions