How to get speed in android app using Location or accelerometer or some other way

前端 未结 4 1412
孤城傲影
孤城傲影 2020-12-24 00:02

I am working on app and try to get the speed and distance travelled by the user. I have used Google Play services location class to get the speed but it always returns me 0.

4条回答
  •  猫巷女王i
    2020-12-24 00:16

    I had to deal with same problem, what you can do is to use Location Strategies code.

    Then, on each update of location, you save the time of the current update. So, you will have the previous and current location, and time of update.

    Then you calculate the distance in meters between those two locations (the old and new one)

    private static long calculateDistance(double lat1, double lng1, double lat2, double lng2) {
        double dLat = Math.toRadians(lat2 - lat1);
        double dLon = Math.toRadians(lng2 - lng1);
        double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
                + Math.cos(Math.toRadians(lat1))
                * Math.cos(Math.toRadians(lat2)) * Math.sin(dLon / 2)
                * Math.sin(dLon / 2);
        double c = 2 * Math.asin(Math.sqrt(a));
        long distanceInMeters = Math.round(6371000 * c);
        return distanceInMeters;
    }
    

    So, then you have the distance and the time difference, I think it wouldn't be a big deal to get the speed.

提交回复
热议问题