获取位置距离和速度android

时间:2017-08-22 05:36:06

标签: android geolocation gps distance

您好我正在尝试每5秒获取一次位置并计算速度和总距离或行程,但它没有给出确切的距离和速度,下面是我的代码,请帮忙。 TIA

public class LocationUpdater extends Service implements GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener{

private double latitude ;
private double longitude ;
Session session;
Context context;
LocationRequest mLocationRequest;

private static final int MILLISECONDS_PER_SECOND = 1000;

public static final int UPDATE_INTERVAL_IN_SECONDS = 5;
private static final long UPDATE_INTERVAL =
        MILLISECONDS_PER_SECOND * UPDATE_INTERVAL_IN_SECONDS;

private static final int FASTEST_INTERVAL_IN_SECONDS = 10;
private static final long FASTEST_INTERVAL =
        MILLISECONDS_PER_SECOND * FASTEST_INTERVAL_IN_SECONDS;

private static final int DESIRED_ACCURACY = 10;
private static final float SMALLEST_DISPLACEMENT = 10f;

/**
 * Provides the entry point to Google Play services.
 */
protected GoogleApiClient mGoogleApiClient;

public LocationUpdater() {
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    context = LocationUpdater.this;
    session = Session.getSession(context);
    buildGoogleApiClient();
    mGoogleApiClient.connect();
    return START_STICKY;
}

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

@Override
public IBinder onBind(Intent intent) {
    // TODO: Return the communication channel to the service.
    throw new UnsupportedOperationException("Not yet implemented");
}

@Override
public void onConnected(Bundle bundle) {
    try{


        mLocationRequest = LocationRequest.create();
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setSmallestDisplacement(SMALLEST_DISPLACEMENT);

        requestLocationUpdate();

    }catch (SecurityException ex){
        ex.printStackTrace();
    }


}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    mGoogleApiClient.connect();
}

@Override
public void onDestroy() {
    super.onDestroy();
    if(session.getTrip_status().equalsIgnoreCase(Utils.trip_status_started))
        startService(new Intent(LocationUpdater.this,LocationUpdater.class));
}

我能够获得结果但是更新并且不准确且根本不光滑。如果这是正确的做法,请告诉我,否则我应该尝试别的。

以下是我的位置更新代码

 private void fetchMyLocation(){
    try{
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {

                if (location != null) {
                    latitude = location.getLatitude();
                    longitude = location.getLongitude();

                    Log.wtf("ankit","accuracy "+location.getAccuracy());

                    if (location.hasAccuracy()  && location.getAccuracy() <= DESIRED_ACCURACY) {
                        // This is your most accurate location.
                        Log.wtf("ankit","latitude:::"+latitude);
                        Log.wtf("ankit","longitude:::"+longitude);

                        session.setCurrentLatitude(""+latitude);
                        session.setCurrentLongitude(""+longitude);

                        if(session.getTrip_status().equalsIgnoreCase(Utils.trip_status_started)){
                            updateDistanceAndSpeed(latitude,longitude);
                        } else {
                            UpdateLocationListner.getInstance().changeState(latitude,longitude,"");
                        }
                    }

                }


            }
        });
    }catch (SecurityException ex){
        ex.printStackTrace();
    }
}

这就是我计算速度和距离的方法

    // update speed and distance

private void updateDistanceAndSpeed(double latitude,double longitude){

    long currentTimeMills = System.currentTimeMillis();

        if (session.getLastLatitude().equalsIgnoreCase("")
                && session.getLastLongitude().equalsIgnoreCase("")) {
            session.setLastLatitude(""+latitude);
            session.setLastLongitude(""+longitude);
        }else {
            synchronized (this){
                try{
                    String lat = ""+latitude;
                    String lng = ""+longitude;
                    double speed = 0;

                    if(!lat.equalsIgnoreCase(session.getLastLatitude())
                            && !lng.equalsIgnoreCase(session.getLastLongitude())){

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

                        locationA.setLatitude(latitude);
                        locationA.setLongitude(longitude);

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

                        locationB.setLatitude(Double.parseDouble(session.getLastLatitude()));
                        locationB.setLongitude(Double.parseDouble(session.getLastLongitude()));

                        if(session.getDistance().equalsIgnoreCase(""))
                            session.setDistance("0");

                        Log.wtf("ankit","total distance:"+session.getDistance());

                        float lastDistance = Float.parseFloat(session.getDistance());

                        float distance[] = new float[1];

                        Location.distanceBetween(latitude, longitude,
                                Double.parseDouble(session.getLastLatitude()),
                                Double.parseDouble(session.getLastLongitude()), distance);



                        if(!session.getLastTimeStamp().equalsIgnoreCase("")){
                            long lastTime = Long.parseLong(session.getLastTimeStamp());
                            long timeDifference = currentTimeMills - lastTime;

                            long diffInSec = TimeUnit.MILLISECONDS.toSeconds(timeDifference);
                            speed = distance[0]/diffInSec;
                        } else {
                            speed = 0;
                        }

                        speed = speed*3.6;
                        speed = Utils.round(speed,2);

                        float roundDistance = Utils.round(distance[0],2);
                        Log.wtf("ankit","roundDistance"+roundDistance);
                        float final_distance = lastDistance+roundDistance;
                        UpdateLocationListner.getInstance().changeState(latitude,longitude,""+speed+"/"+final_distance);
                        session.setDistance(""+final_distance);


                    } else {
                        UpdateLocationListner.getInstance().changeState(latitude,longitude,"0/0");
                    }
                    // send speed


                }catch (Exception ex){
                    ex.printStackTrace();
                }
            }
            session.setLastLatitude(""+latitude);
            session.setLastLongitude(""+longitude);
            session.setLastTimeStamp(""+currentTimeMills);
        }



}

1 个答案:

答案 0 :(得分:1)

你只需要传递纬度和经度

public void setLatLng(LatLng origins, LatLng destinations) {
        url = "http://maps.googleapis.com/maps/api/distancematrix/json?" +
                "origins=" + origins.latitude + "," + origins.longitude + "" +
                "&destinations=" + destinations.latitude + "," + destinations.longitude + "" +
                "&mode=driving" +
                "&language=en-EN" +
                "&sensor=false";
    }

在这里处理此URL的响应,给出两个纬度和经度之间的距离和时间,所以现在需要计算速度和你使用的速度

速度=距离/时间