2014-11-05 83 views
-1

我對Java很新穎& Android和我有一些代碼問題。Android GPS精確距離測量

location1.distanceTo(location2)方法是否也考慮海拔變化計算距離?

另一個問題是,儘管我沒有移動設備,但測得的距離發生了變化。 這是我的代碼:

public class GpsCalculator{ 
public Activity activity; 
private LocationManager locationManager = null; 
private Location previousLocation = null; 
private double totalDistance = 0D; 
private Context context; 
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; // 1 meter 
private static final long MIN_TIME_BW_UPDATES = 1000; // 1 second 
TextView distance_tracker; 

public GpsCalculator(TextView dt) { 
    distance_tracker = dt; 
} 


public void run(Context act){ 
    context = act; 
    // Get the location manager 
    locationManager = (LocationManager) context.getSystemService(Service.LOCATION_SERVICE); 

    // Add new listeners with the given params 
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListener); // Network location 
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListener); // Gps location 
} 

public void stop(){ 
    locationManager.removeUpdates(locationListener); 
} 
DecimalFormat df = new DecimalFormat("#"); 
private LocationListener locationListener = new LocationListener(){ 
    @Override 
    public void onLocationChanged(Location newLocation){ 
     if (previousLocation != null){ 
      GpsCalculator.this.totalDistance += previousLocation.distanceTo(newLocation); 
     } 

     // Update stored location 
     GpsCalculator.this.previousLocation = newLocation; 

     CharSequence text = Double.toString(totalDistance); 
     int duration = Toast.LENGTH_SHORT; 

     Toast toast = Toast.makeText(context, text, duration); 
     toast.show(); 

     distance_tracker.setText(df.format(totalDistance)+ " m"); 
    } 

    @Override 
    public void onProviderDisabled(String provider) {} 

    @Override 
    public void onProviderEnabled(String provider) {} 

    @Override 
    public void onStatusChanged(String provider, int status, Bundle extras) {} 
}; } 

我想提一提的是,精度問題堅持用或不用網絡提供商監聽。

結論

的代碼是正確的,但GPS數據的準確性是沒有的。我從Carsten的回答下的評論中理解了這一點。

回答

1

位置對象通常還包含高度信息,因此要考慮高程。

更新之間的位置是否更改?我會這樣認爲,因爲它在你的案例中每秒更新一次。

+0

那麼,我該如何優化代碼,如果我不動,距離不會改變? – 2014-11-05 12:36:22

+0

我會堅持GPS提供商,增加MIN_DISTANCE_CHANGE_FOR_UPDATES並增加MIN_TIME_BW_UPDATES。由於您可能也會從其他來源獲取更新,因此如果上次更新與新版本之間的距離足夠滿足您的用途,則也值得驗證自己。 – Carsten 2014-11-05 12:47:10

+0

感謝您提醒我GPS衛星的精度不是1米。我正在做戶外活動,所以我想我會騎自行車並騎一下:) – 2014-11-05 13:02:13