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

前端 未结 4 1416
孤城傲影
孤城傲影 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条回答
  •  清歌不尽
    2020-12-24 00:34

    public static double getSpeed(Location currentLocation, Location oldLocation)
    {
        double newLat = currentLocation.getLatitude();
        double newLon = currentLocation.getLongitude();
    
        double oldLat = oldLocation.getLatitude();
        double oldLon = oldLocation.getLongitude();
    
        if(currentLocation.hasSpeed()){
            return currentLocation.getSpeed();
        } else {
            double radius = 6371000;
            double dLat = Math.toRadians(newLat-oldLat);
            double dLon = Math.toRadians(newLon-oldLon);
            double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
                    Math.cos(Math.toRadians(newLat)) * Math.cos(Math.toRadians(oldLat)) *
                            Math.sin(dLon/2) * Math.sin(dLon/2);
            double c = 2 * Math.asin(Math.sqrt(a));
            double distance =  Math.round(radius * c);
    
            double timeDifferent = currentLocation.getTime() - oldLocation.getTime();
            return distance/timeDifferent;
        }
    }
    

提交回复
热议问题