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:
String provider = initLocManager(); if (provider == null) return false; LocationListener locListener = new LocationListener() { public void onLocationChanged(Location location) { updateWithNewLocation(location, interval, startId); Log.i(getString(R.string.logging_tag), "speed =" + location.getSpeed()); } public void onProviderDisabled(String provider){ updateWithNewLocation(null, interval, startId); } public void onProviderEnabled(String provider) {} public void onStatusChanged(String provider, int status, Bundle extras) {} }; _locManager.requestLocationUpdates(provider, interval, DEFAULT_GPS_MIN_DISTANCE, locListener); private String initLocManager() { String context = Context.LOCATION_SERVICE; _locManager = (LocationManager) getSystemService(context); Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_FINE); criteria.setAltitudeRequired(false); criteria.setBearingRequired(true); criteria.setSpeedRequired(true); criteria.setCostAllowed(true); //criteria.setPowerRequirement(Criteria.POWER_LOW); String provider = _locManager.getBestProvider(criteria, true); if (provider == null || provider.equals("")) { displayGPSNotEnabledWarning(this); return null; } return provider; }
I tried to play the Criteria with but no success. Does anyone have an idea what is the problem?
location.getSpeed() only returns what was set with location.setSpeed(). This is a value that you can set for a location object.
To calculate the speed using GPS, you'll have to do a little math:
Speed = distance / time
So you would need to do:
(currentGPSPoint - lastGPSPoint) / (time between GPS points)
All converted to ft/sec, or however you want to show the speed. This is how I did it when I made a runner app.
More specifically, you'll need to calculate for absolute distances:
(sqrt((currentGPSPointX - lastGPSPointX)^2) + (currentGPSPointY - lastGPSPointY)^2)) / (time between GPS points)
It might help to make a new TrackPoint class or something, which keeps the GPS location and time it was taken inside.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With