why getSpeed() always return 0 on android

前端 未结 11 1278
半阙折子戏
半阙折子戏 2020-11-28 07:35

I need to get the speed and heading from the gps. However the only number i have from location.getSpeed() is 0 or sometimes not available. my code:

         


        
11条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-28 08:17

    Imbru's answer looks really good, but it is not very helpful if you are working with units.

    Here's what I did to calculate the speed in meters per second (m/s).

    object : LocationListener() {
        var previousLocation: Location? = null
    
        override fun onLocationChanged(location: Location) {
            val speed = if (location.hasSpeed()) {
                location.speed
            } else {
                previousLocation?.let { lastLocation ->
                    // Convert milliseconds to seconds
                    val elapsedTimeInSeconds = (location.time - lastLocation.time) / 1_000.
                    val distanceInMeters = lastLocation.distanceTo(location)
                    // Speed in m/s
                    distanceInMeters / elapsedTimeInSeconds
                } ?: 0.0
            }
            previousLocation = location
    
            /* There you have it, a speed value in m/s */
            functionThatUsesSpeedInMeterPerSecond(speed)
    
            . . .
    
        }
    
        . . .
    
    }
    

提交回复
热议问题