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:
I also encountered this problem before, I hope this can help.
It returns 0 because your device cannot get a lock on the GPS, or cannot connect to the GPS.
I tried to get the speed using an older lenovo device and it returns 0 because it cannot lock on a gps.
I tried using a samsung galaxy nexus and it returned my speed(has a better GPS sensor).
The GPS sensor in your phone might not be good or you are in an area that has a weak GPS signal such as inside a house or building.
I basicaslly calculate the instantaneous speed and then use the setSpeed() method to add it in the location. Its pretty accurate because I compared it inside a vehicle where I could check the tachymeter.
private double calculateInstantaneousSpeed(Location location) {
double insSpeed = 0;
if (y1 == null && x1 <= -1) {
//mark the location y1 at time x1
y1 = location;
x1 = duration.getDurationAsSeconds();
} else {
//mark the location y2 at time x2
y2 = location;
x2 = duration.getDurationAsSeconds();
//calculate the slope of the curve (instantaneous speed)
dy = y1.distanceTo(y2);
dx = x2 - x1;
insSpeed = dy / dx;
y1 = y2;
x1 = x2;
}
Singleton.getInstance().instantaneousSpeedSamples.add(insSpeed);
//System.out.println("Instantaneous Speed m/s: "+insSpeed);
return insSpeed;
}
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)
. . .
}
. . .
}
(1) I believe you can use the requestLocationUpdates()
method and then create a LocationListener class with an onLocationChange method set to display getSpeed()
. This is how i recently saw it done with Location.getLatitude and Location.getLongitude, so I believe you could just use getSpeed() the same way, correct?
(2) After just reading the eclipse description window, though, I see it says exactly what the previous person said: "if hasSpeed() is false, 0.0f is returned." But maybe this will help: http://www.ehow.com/how_5708473_convert-latitude-feet.html :)
Hey I too was suffering from the same but now I have got it solved ! Just multiply the value by 18/5 , it gives almost the accurate value.
speed=location.getSpeed()*18/5
Also specify the interval
as 1000*2
and fastest interval
as 1000*1
for more accuracy