由于GPS位置错误,无法在不同位置之间获得适当的速度

时间:2015-12-16 12:24:31

标签: android google-maps gps

我正在尝试在两个位置之间找到速度,但发现 GPS位置不准确。我在同一个地方,它一直在提供不同的位置。例如,它为我提供了距离我大约200KM的位置。

public class LocationTracker extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener, SensorEventListener {

// LogCat tag
private static final String TAG = "LocationTracker";

private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;
private static int UPDATE_INTERVAL = 5000; // 5 sec
private static int FATEST_INTERVAL = 2000; // 2 sec
private static int DISPLACEMENT = 2; // 2 meters
private Context context;
private SharedPreferences sp;

// Location updates intervals in sec
private Location mLastLocation;

private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private double latitude, longitude;
private boolean firstLocation = false;

private float speed;


public LocationTracker(Context ctx, boolean firstLocation) {

    context = ctx;

    sp = context.getSharedPreferences(Utility.SHARED_PREFS, MODE_PRIVATE);

    this.firstLocation = firstLocation;

    // First we need to check availability of play services
    if (checkPlayServices()) {

        createLocationRequest();
        buildGoogleApiClient();


        if (mGoogleApiClient != null)
            mGoogleApiClient.connect();

    }

}


@Override
public void onConnectionSuspended(int i) {
    mGoogleApiClient.connect();
}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {

}

/**
 * Creating google api client object
 */
protected synchronized void buildGoogleApiClient() {

    mGoogleApiClient = new GoogleApiClient.Builder(context)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API).build();
}

/**
 * Method to verify google play services on the device
 */
private boolean checkPlayServices() {

    int resultCode = GooglePlayServicesUtil
            .isGooglePlayServicesAvailable(context);

    if (resultCode != ConnectionResult.SUCCESS) {

        if (GooglePlayServicesUtil.isUserRecoverableError(resultCode))
            Utility.showLog(TAG, "Something went wrong with error code :" + resultCode);
        else
            Utility.showLog(TAG,
                    "This device is not supported.");

        // stopLocationUpdates();
        return false;
    }

    return true;
}


/**
 * Creating location request object
 */
protected void createLocationRequest() {

    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(UPDATE_INTERVAL);
    mLocationRequest.setFastestInterval(FATEST_INTERVAL);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    mLocationRequest.setSmallestDisplacement(DISPLACEMENT); // 10 meters

}

/**
 * Starting the location updates
 */
public void startLocationUpdates() {

    Utility.showLog(TAG, "Starting Location Updates");

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

}

/**
 * Stopping location updates
 */
public void stopLocationUpdates() {

    Utility.showLog(TAG, "Stopping Location Updates");


    if (mGoogleApiClient != null) {

        LocationServices.FusedLocationApi.removeLocationUpdates(
                mGoogleApiClient, this);

        if (mGoogleApiClient.isConnected())
            mGoogleApiClient.disconnect();

    }
    stopSelf();

}


/**
 * Function to get latitude
 */
public double getLatitude() {

    // return latitude
    return latitude;
}

/**
 * Function to get longitude
 */
public double getLongitude() {

    // return longitude
    return longitude;
}

@Override
public void onConnected(Bundle bundle) {

    Utility.showLog(TAG, "Google API Connected");


    // Once connected with google api, get the location
    updateLocation();
    startLocationUpdates();
}

@Override
public void onLocationChanged(Location location) {

    // Assign the new location
    mLastLocation = location;
    updateLocation();

}

@Override
public IBinder onBind(Intent intent) {
    return null;
}

/**
 * Method to display the location on UI
 */
private void updateLocation() {

    mLastLocation = LocationServices.FusedLocationApi
            .getLastLocation(mGoogleApiClient);

    if (mLastLocation != null) {

        if (firstLocation) {

            sp.edit().putString("last_latitude", String.valueOf(mLastLocation.getLatitude())).commit();
            sp.edit().putString("last_longitude", String.valueOf(mLastLocation.getLongitude())).commit();
            sp.edit().putLong("last_location_time", System.currentTimeMillis()).commit();

            firstLocation = false;

            Utility.showLog(TAG, "Last Latitude : " + mLastLocation.getLatitude());
            Utility.showLog(TAG, "Last Longitude : " + mLastLocation.getLongitude());

        }

        latitude = mLastLocation.getLatitude();
        longitude = mLastLocation.getLongitude();

        heading = mLastLocation.getBearing();
        altitude = mLastLocation.getAltitude();

        Utility.showLog(TAG, " Latitude : " + latitude);
        Utility.showLog(TAG, " Longitude : " + longitude);

        Utility.showLog(TAG, "Heading :" + heading);
        Utility.showLog(TAG, "Altitude :" + altitude);


    } else
        Utility.showLog(TAG, "Couldn't get the location. Make sure location is enabled on the device");
}

@Override
public void onDestroy() {
    super.onDestroy();

    Utility.showLog(TAG, "Location Tracker Stopped");
}

/**
 * Function to get Speed
 */

public double getSpeed() {


    double previousLatitude = Double.parseDouble(sp.getString("last_latitude", "0.0"));
    double previousLongitude = Double.parseDouble(sp.getString("last_longitude", "0.0"));

    Utility.showLog(TAG, "Old Latitude :" + previousLatitude);
    Utility.showLog(TAG, "Old Longitude :" + previousLongitude);

    Utility.showLog(TAG, "New Latitude :" + latitude);
    Utility.showLog(TAG, "New Longitude :" + longitude);

    Location sourceLocation = new Location("A");
    sourceLocation.setLatitude(previousLatitude);
    sourceLocation.setLongitude(previousLongitude);

    Location destinationLocation = new Location("B");
    destinationLocation.setLatitude(latitude);
    destinationLocation.setLongitude(longitude);


    double distance = sourceLocation.distanceTo(destinationLocation);

    Utility.showLog(TAG, "Distance =" + distance);

    float differenceInTime = (float) ((System.currentTimeMillis() - sp.getLong("last_location_time", 0)) / 1000);

    Utility.showLog(TAG, "Current Time :" + System.currentTimeMillis());
    Utility.showLog(TAG, "Last Time :" + sp.getLong("last_location_time", 0));

    Utility.showLog(TAG, "Difference in Time " + differenceInTime);

    double mps = distance / differenceInTime;
    double kph = (mps * 3600) / 1000;

    return kph;
}

}

1 个答案:

答案 0 :(得分:0)

请检查获得的位置的准确性。如果准确度值很高(很高取决于你的决定),那么忽略它。

您可以使用

获得准确性
location.getAccuracy();

当您在建筑物内时,您的定位精度有时可能会达到2公里左右。在这种情况下你可以忽略。这种精确度取决于提供结果的卫星数量。