Search code examples
androidgoogle-mapsandroid-gps

Calculate average speed from array of Coordinates


     //Global var
     ArrayList<LatLng> points = new ArrayList<>(); 

//--------------------------------------------------------------------------------------

public void onLocationChanged(final Location location) {
    //Adds a marker on the current position found in LatLng
    myCoordinates = new LatLng(location.getLatitude(), location.getLongitude());

    //Sets the marker to the position of LatLng and zooms the camera in on the location
    LocationMarker.setPosition(myCoordinates);
    mMap.moveCamera(CameraUpdateFactory.newLatLng(myCoordinates));
    float zoomLevel = 12.0f;
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(myCoordinates, zoomLevel));

    //Adds marker on each location update
    points.add(myCoordinates);

    mMap.addMarker(new MarkerOptions().position(points.get(0))
            .title("Starting Location")
            .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW)));

    //Draws a polyline between the location updates stored in points.
    mMap.addPolyline(new PolylineOptions()
            .addAll(points)
            .width(5)
            .color(Color.RED));

    //gets speed from Location and converts it to Km/h
    speedText.setText(String.format("%.0f - Km/h", location.getSpeed() * 3.6));

}

This is my onLocationChanged function. This stores the coordinates into my array called points every time it updates. It also draws and a Polyline on each update, calculates my speed in km/h and adds a marker at my array location [0] which is my starting location. This all works fine and perfect for what I need to it do.

Is it possible to calculate the average speed from this?


Solution

  • You only need to create another global list and insert the value of getSpeed();

    speedArray.add(Double.parseDouble(location.getSpeed()));
    

    And create a function that its called in the end of onLocationChanged and it calculates the average speed everytime;