why getSpeed() always return 0 on android

前端 未结 11 1270
半阙折子戏
半阙折子戏 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:01

    There is my custom LocationListener used to get speed manually and by location object if has speed.

     new LocationListener() {
            private Location mLastLocation;
    
            @Override
            public void onLocationChanged(Location pCurrentLocation) {
                //calcul manually speed
                double speed = 0;
                if (this.mLastLocation != null)
                    speed = Math.sqrt(
                            Math.pow(pCurrentLocation.getLongitude() - mLastLocation.getLongitude(), 2)
                                    + Math.pow(pCurrentLocation.getLatitude() - mLastLocation.getLatitude(), 2)
                    ) / (pCurrentLocation.getTime() - this.mLastLocation.getTime());
                //if there is speed from location
                if (pCurrentLocation.hasSpeed())
                    //get location speed
                    speed = pCurrentLocation.getSpeed();
                this.mLastLocation = pCurrentLocation;
                ////////////
                //DO WHAT YOU WANT WITH speed VARIABLE
                ////////////
            }
    
            @Override
            public void onStatusChanged(String s, int i, Bundle bundle) {
    
            }
    
            @Override
            public void onProviderEnabled(String s) {
    
            }
    
            @Override
            public void onProviderDisabled(String s) {
    
            }
        };
    

提交回复
热议问题