位置距离计算得到错误的值

时间:2018-03-14 17:55:02

标签: android android-gps fusedlocationproviderapi

我正在尝试以米为单位跟踪用户距离,但有时给定的距离远远超过用户实际行进的距离。我想也许是因为曲线或类似的东西,但想知道我做错了什么。这是我的代码:

public class MainActivity extends AppCompatActivity {

    private FusedLocationProviderClient mFusedLocationClient;
    private LocationCallback mLocationCallback;
    private LatLng mLastKnownLatLng;
    private float[] mResults = new float[]{0};
    private float mDistance = 0;

    @Override
    public void onCreate() {
        super.onCreate();
        setContentView(R.layout.main);

        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
        startLocationUpdates();
        createLocationCallback();
    }

    protected void startLocationUpdates() {

        LocationRequest locationRequest = new LocationRequest();
        locationRequest.setInterval(5000);
        locationRequest.setFastestInterval(1000);
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

        if (checkLocationPermission())
            mFusedLocationClient.requestLocationUpdates(locationRequest, mLocationCallback,
                Looper.myLooper());
    }

    private void createLocationCallback() {
        mLocationCallback = new LocationCallback() {
            @Override
            public void onLocationResult(LocationResult locationResult) {
                super.onLocationResult(locationResult);

                Location location = locationResult.getLastLocation();

                if (mLastKnownLatLng == null)
                    mLastKnownLatLng = new LatLng(location.getLatitude(), location.getLongitude());

                if ((mLastKnownLatLng.latitude != location.getLatitude()
                    && mLastKnownLatLng.longitude != location.getLongitude())
                    && location.getAccuracy() < 50) {

                    Location.distanceBetween(mLastKnownLatLng.latitude, mLastKnownLatLng.longitude,
                        location.getLatitude(), location.getLongitude(), mResults);

                    mDistance += mResults[0];

                    mLastKnownLatLng = new LatLng(location.getLatitude(), location.getLongitude());
                }
            }
        };
    }
}

1 个答案:

答案 0 :(得分:1)

你应该试试

Location locationA = new Location("point A");

locationA.setLatitude(latA);
locationA.setLongitude(lngA);

Location locationB = new Location("point B");

locationB.setLatitude(latB);
locationB.setLongitude(lngB);

float distance = locationA.distanceTo(locationB);

//in your case 

mLastKnownLatLng.distanceTo(location)