Google Play服务位置API - 计算距离

时间:2015-10-15 08:24:10

标签: java android android-studio gps google-play-services

我一直在关注https://developer.android.com/training/location/index.html教程。

我的班级实施了新的Google位置API:

public class GPSTracker implements LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
    private final Context context;
    private TextView distanceTextView;
    private GoogleApiClient mGoogleApiClient;
    private LocationRequest mLocationRequest;
    private Location mLastLocation;
    private double totalMeters = 0;

    public GPSTracker(Context context, TextView distanceTextView) {
        this.context = context;
        this.distanceTextView = distanceTextView;
        buildGoogleApiClient();
    }

    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(context)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();

        mGoogleApiClient.connect();
    }

    @Override
    public void onLocationChanged(Location location) {
        double distance = mLastLocation.distanceTo(location);
        mLastLocation = location;
        totalMeters += distance;
        distanceTextView.setText(totalMeters + "");
    }

    @Override
    public void onConnected(Bundle bundle) {
        mLocationRequest = LocationRequest.create();
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setInterval(1000); // Update location every second

        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);

        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Toast.makeText(context, connectionResult.getErrorMessage(), Toast.LENGTH_SHORT).show();
    }
}

一切似乎都在完美无缺,但是当我的手机完全没有移动时,每次执行onLocationChanged方法时,totalDistance仍然会上升0.2-0.3米。

我们非常感谢任何可以预防这种情况的解决方案。

1 个答案:

答案 0 :(得分:2)

不要忘记GPS不准确。通常会有几米的距离,所以这样的读数不正确是很自然的。虽然旧的LocationManager具有minDistance设置,但遗憾的是LocationRequest没有。

几种解决方案:如果速度为零,您可以检查速度,这可能表示用户实际上没有移动。您也可以手动检查旧位置是否与新位置几乎相同(在您的情况下,0.3m似乎是一个很好的阈值)并丢弃该读数。最后但并非最不重要的是,您可以设置ActivityRecognitionApi活动监听器,以确定用户实际上是在移动还是静止。