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

Java Google Play服务位置API-计算距离,java,android,android-studio,gps,google-play-services,Java,Android,Android Studio,Gps,Google Play Services,我一直在学习教程 下面是我的课程,它实现了新的谷歌定位API: public class GPSTracker implements LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { private final Context context; private TextView distanceTextView; priva

我一直在学习教程

下面是我的课程,它实现了新的谷歌定位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方法时,总距离仍会增加0.2-0.3米


高度赞赏任何防止这种情况的解决方案。

不要忘记GPS不是精确的定位点。通常会偏离几米,所以很自然会出现这样的错误读数。虽然旧的LocationManager有MindRestance设置,但不幸的是没有

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