2016-05-27 7 views
1

Я пробовал getLastKnownLocation(), но я обнаружил, что он не смог обеспечить точное местоположение, иногда, и он выбирает неправильные местоположения, в противном случае это хорошо.Как получить точное местоположение в Android?

Может ли кто-нибудь мне помочь? Я новичок на андроид студии

Это мой GPS Tracker код ниже ....

if (isGPSEnabled) 
{ 
    locationManager.requestLocationUpdates(
      LocationManager.GPS_PROVIDER, 
      MIN_TIME_BW_UPDATES, 
      MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 

    Log.d("GPS Enabled", "GPS Enabled"); 

    if (locationManager != null) 
    { 
     location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
     updateGPSCoordinates(); 
    } 
} 
} else if (isNetworkEnabled) { 
locationManager.requestLocationUpdates(
     LocationManager.NETWORK_PROVIDER, 
     MIN_TIME_BW_UPDATES, 
     MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 

Log.d("Network", "Network"); 

if (locationManager != null) 
{ 
    location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
    updateGPSCoordinates(); 
} 
} 

// ... 

@Override 
public void onLocationChanged(Location location) 
{ 
this.location = location; 
updateGPSCoordinates(); 
} 
+0

Что вы имеете в виду под "неправильном месте"? GPS не является на 100% точным и имеет некоторую ошибку. Это также имеет значение, если GPS является неудовлетворительным или наружным. – TDG

+0

Я проводил много испытаний в эти недели, и я заметил, что точность во многом зависит от бренда телефона. Некоторые из них лучше построили GPS-чипы, чем другие ... Кроме того, есть некоторая проблема с ОС Lollipop, как указано здесь: https://code.google.com/p/android/issues/detail?id=81140 – Jaythaking

+0

неправильное расположение означает, что иногда его показывает ранее выбранное местоположение, а не обновленное. у вас есть идея получить обновленное местоположение (не LastKnownLocation). –

ответ

2

Существует очень полезная страница на Android Developper documentation, я надеюсь, что это поможет. Для моей цели, я должен был настроить его немного, но основная идея остается той же:

Можно было бы ожидать, что самое последнее исправление место является наиболее точным . Однако, поскольку точность определения местоположения меняется, последнее исправление не всегда является лучшим. Вы должны включить логику для , выбрав исправления местоположения на основе нескольких критериев. Критерии также различаются в зависимости от вариантов использования приложения и поля .

private static final int TWO_MINUTES = 1000 * 60 * 2; 

/** Determines whether one Location reading is better than the current Location fix 
    * @param location The new Location that you want to evaluate 
    * @param currentBestLocation The current Location fix, to which you want to compare the new one 
    */ 
protected boolean isBetterLocation(Location location, Location currentBestLocation) { 
    if (currentBestLocation == null) { 
     // A new location is always better than no location 
     return true; 
    } 

    // Check whether the new location fix is newer or older 
    long timeDelta = location.getTime() - currentBestLocation.getTime(); 
    boolean isSignificantlyNewer = timeDelta > TWO_MINUTES; 
    boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES; 
    boolean isNewer = timeDelta > 0; 

    // If it's been more than two minutes since the current location, use the new location 
    // because the user has likely moved 
    if (isSignificantlyNewer) { 
     return true; 
    // If the new location is more than two minutes older, it must be worse 
    } else if (isSignificantlyOlder) { 
     return false; 
    } 

    // Check whether the new location fix is more or less accurate 
    int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy()); 
    boolean isLessAccurate = accuracyDelta > 0; 
    boolean isMoreAccurate = accuracyDelta < 0; 
    boolean isSignificantlyLessAccurate = accuracyDelta > 200; 

    // Check if the old and new location are from the same provider 
    boolean isFromSameProvider = isSameProvider(location.getProvider(), 
      currentBestLocation.getProvider()); 

    // Determine location quality using a combination of timeliness and accuracy 
    if (isMoreAccurate) { 
     return true; 
    } else if (isNewer && !isLessAccurate) { 
     return true; 
    } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) { 
     return true; 
    } 
    return false; 
} 

/** Checks whether two providers are the same */ 
private boolean isSameProvider(String provider1, String provider2) { 
    if (provider1 == null) { 
     return provider2 == null; 
    } 
    return provider1.equals(provider2); 
} 
Смежные вопросы