android工作室存储速度和计算距离

时间:2016-03-24 09:17:02

标签: android

我有一个requestLocationUpdates =>在每5秒,该位置将更新。我想计算每5秒的距离,然后将其存储到一个数组中。此外,我想将location.getSpeed存储到一个数组中,这样我就可以使用数组中保存的速度在下一个界面中绘制图形。 这是我的代码:

 private void updateWithNewLocation(Location location) {
    String where = "";
    if (location != null) {

        double lng = location.getLongitude();

        double lat = location.getLatitude();

        float speed = location.getSpeed();

        long time = location.getTime();
        String timeString = getTimeString(time);

        where = "Lng: " + lng +
                "\nLat: " + lat +
                "\nSpeed: " + speed +
                "\nTime: " + timeString +
                "\nProvider: " + "gps";


        showMarkerMe(lat, lng);
        cameraFocusOnMe(lat, lng);
        trackToMe(lat, lng);

    }else{
        where = "No location found.";
    }


    txt.setText(where);
}

1 个答案:

答案 0 :(得分:0)

关于storing data您有不同的选择。您可以使用database来显示数据,阅读它并在下次使用应用时再次阅读。如果您希望数据仅在当前应用程序生命周期中持久存在,我建议使用ArrayList个自定义对象。 ArrayList<LocationObject>用法的简短示例:

public class LocationObject {
    private double lng;
    private double lat;
    private float speed;
    private long time;

    public LocationObject(long time, double lng, double lat, float speed) {
        this.time = time;
        this.lat = lat;
        this.lng = lng;
        this.speed = speed;
    }

    //put getters  & setters here, press `Alt` and `Insert`, choose the getters and setters

}

在您的投放Activity中,全局初始化ArrayList(不在方法内部,但在Activity.class内:

private ArrayList<LocationObject> locationList;

//in onCreate:
locationList = new ArrayList<LocationObject>();

//whenever you retrieve a location, create a LocationObject and store it into the List:
LocationObject currentLocation = new LocationObject(time, lng, lat, speed);
locationList.add(currentLocation);

现在,如果您想获得最后2个位置,只需在列表中访问它们:

LocationObject lastLocation = locationList.get(locationList.size() - 2);
LocationObject currentLocation = locationList.get(locationList.size() - 1);

//to get the latitude, don't forget to create the getters&setters in your LocationObject.class!
double lastLat = lastLocation.getLat();

编辑:要仅存储最后一个值,只需将值分配给全局声明的变量:

private Location oldLocation;
private float[] results;
private ArrayList<float> speedList;


//in oncreate: 
speedList = new ArrayList<Float>();


private void updateWithNewLocation(Location location) {
String where = "";
results = new float[100]; //[100] means there can be 100 entries - decrease or increase the number depending on your output
if (location != null) {

    double lng = location.getLongitude();
    double lat = location.getLatitude();
    float speed = location.getSpeed();
    long time = location.getTime();
    String timeString = getTimeString(time);

    speedList.add(speed);

    if(oldLocation != null){
        Location.distanceBetween(oldLocation.getLatitude(), oldLocation.getLongitude(), lat, lng, results);
    } 
    oldLocation = location;