Search code examples
androidgpslocationandroid-mapviewoverlays

trying to get the most accurate device location from GPS or Network in Android


I am trying to determine the most accurate location of a device, in the shortest time possible.

I am storing the data as a geopoint, and have it displayed on a mapview.

The last time I activated the GPS on my device and let it get a location lock, i was approx 80 miles from where I am now.

I have a location manager setup and a location listener.

If I do this, I get NULL.

  myLocOverlay = new MyLocationOverlay(this, mapView);
  GeoPoint test = myLocOverlay.getMyLocation();

but in the next couple of lines;

  myLocOverlay.enableMyLocation();      
  mapView.getOverlays().add(myLocOverlay);

With this, the overlay on the map shows the current location. It is using the Network provider, but is also attempting to get a GPS fix (it can't as I am indoors and no where near the top floor).

If I construct the geopoint like this;

    if(lm.getLastKnownLocation("gps") != null) 
    {
     test = new GeoPoint(
        (int) (lm.getLastKnownLocation("gps").getLatitude() * 1E6), 
        (int) (lm.getLastKnownLocation("gps").getLongitude() * 1E6));
    }

    else
    {

    if(lm.getLastKnownLocation("network") != null) 
    {
     test = new GeoPoint(
       (int) (lm.getLastKnownLocation("network").getLatitude() * 1E6), 
       (int) (lm.getLastKnownLocation("network").getLongitude() * 1E6));
    }
    //bad things
    }

Then I get confusing results. If I disable the devices GPS provider then the code moves onto the Network Provider and gives me a fairly accurate result. If I enable the GPS provider, then the geopoint comes back as the last place I allowed the device to get a GPS lock.

I want to avoid the above results, and so was looking at using;

GeoPoint test = myLocOverlay.getMyLocation();

BUT as I said above, I just get NULL from that.

Short of getting the geopoints from both GPS and Network and then comparing them, and disregarding the GPS result if it is say 1 mile out of the Network location - i'm a bit stuck. why doesn't getMyLocation() work, shouldnt that return the GeoPoint of what myLocOverlay is showing on the mapview?


Solution

  • It may return null because it hasn't obtained a fix yet. You should register a LocationListener that accepts updates from both the Network and GPS sources. Then, when you get a location update, you can look at the accuracy of the location and decide if you want to use it.