Getting the Speed of the User - getSpeed and casting - android

I am currently trying to get the speed of a user using the GPS (Google Play Location Services).
However, the problem with my code is that the speed is stuck on a very small number - going down to 1.9^E18, basically 0. This value doesn't change even though I move around.
I am currently trying to calculate the speed of the user manually through using speed and time stamps. However, I have also found a function called getSpeed(). I was considering to use it, but there were many complaints I found here that said that it always returned zero.
Firstly - is getSpeed() only used for mock locations, or can it be used safely with location objects obtained by the GPS?
Secondly if getSpeed does not work, I will need to continue obtaining the speed manually. I believe there may be problems with the casting. Can someone help in finding the problem of my current method?
public void onLocationChanged(Location location) {
location.getLatitude();
Toast.makeText(this, "Location Changed", Toast.LENGTH_SHORT).show();
if (settings == null) {
settings = getSharedPreferences(PREFS_NAME, 0);
}
int TimeDifference = (int) (location.getTime() - OldLocation.getTime());
int distance = (int) OldLocation.distanceTo(location);
double speed = distance / TimeDifference;
if (LowerLimit < speed && speed < UpperLimit) {
TimeInstance += TimeDifference;
}
if (TimeInstance>TimeLimit) {
if (!dialogShown) {
dialogShown = true;
ViolationMessage();
TimeInstance = 0;
}
else {
TimeInstance = 0;
}
}
OldLocation = location;
}

Related

How to find the nearby users around the app users locality

Sorry for not providing any sample code because I don't have any idea about how to do this.
I'm coding an Android application which uses Firebase as the backend.
I'm storing the current current user location to mysl db using the fusedlocationapi.
Now, when a user is logged into the application, he/she is given a option to show only the list of user around a radius of 25km (let's assume as an example). Can any one guide me with this feature please.
I don.t wanna do this on client side ...is there any way to so it using mysql
You can use Google Maps Android API utility library
public class DistanceHelper {
private static final Double RADIUS = 25000.0;
public static double getDistance(LatLng user1, LatLng user2){
double distance = SphericalUtil.computeDistanceBetween(user1, user2);
return distance;
}
public static Double getRadius(){
return RADIUS;
}
public static String formatNumber(double distance) {
String unit = "m";
if (distance < 1) {
distance *= 1000;
unit = "mm";
} else if (distance > 1000) {
distance /= 1000;
unit = "km";
}
return String.format("%4.3f%s", distance, unit);
}
}
LatLng user1 = new LatLng(currentUser.getLatitude(), currentUser.getLongitude());
LatLng user2 = new LatLng(otherUser.getLatitude(), otherUser.getLongitude());
Double distance = DistanceHelper.getDistance(user1, user2);
if (distance <= DistanceHelper.getRadius()) {
//code here
}
I store the users' latitude and longitude in FB database using GPS and LocationManager. put the calculation inside your ChildEventListener to retrieve get users inside 25km radius.
However I think this implementation is wrong because the calculations are done on client side so what if you have million or billion of users then you have to compute each one by one on client's device which might cause very slow performance of your app.

Android: How can I get the traveled distance while I'm running?

I'm wrinting a application and I have to show the distance covered while I'm running.
I use the function "public void onLocationChanged" of the LocationListener. When the user tap a botton and start running I want to show the distance he covered updated to the point in which he is located.
I've written this code:
public void onLocationChanged(Location location) {
if(location != null) {
if(location.hasSpeed()){
if(latitude1 == 0 && longitude1 == 0){
latitude1 = (location.getLatitude()*Math.PI)/180;
longitude1 = (location.getLongitude()*Math.PI)/180;
} else{
latitude2 = (location.getLatitude()*Math.PI)/180;
longitude2 = (location.getLongitude()*Math.PI)/180;
distance = (6372.795477598)*Math.acos(Math.sin(latitude1)
*Math.sin(latitude2)+Math.cos(latitude1)
*Math.cos(latitude2)*Math.cos(longitude1-longitude2));
sumDistance += distance;
latitude1 = latitude2;
longitude1 = longitude2;
}
tv.setText("Distance covered=" + sumDistance + " m");
}
}
}
Is it accurated?
Just a Suggestion:
Store the Latitude and Longitude of the start location and the end location when the user clicks the appropriate button.
and then you could use distanceBetween or distanceTo to get the distance between those two geoPoints.
P.S: This may not work if the user will start and end his run at the same point ;)
Addition:
Check this tutorial:
Recently google has improved its location based API's. They have fused the sensors with the location based api's to share examples of how location can be made more accurate (about 4 times more effective) and consume much lesser power (10 times lesser).
Some interesting links for you to go through will be this and video google io.
SO link for how to use the API's here

Location.getBearing always 0.0

I'm using LocationListener and returned Location always has Bearing as 0.0
Is there anything else I need to do?
I also noticed that with 4.0.3 update I rarely have speed reported. Now I just get positions and accuracy/elevation
public void onLocationChanged(Location loc)
{
Log.d(LOG_TAG, "onLocationChanged");
Position position = new Position();
position.PositionGKey = UUID.randomUUID();
position.GPSTime = new Date(loc.getTime());
position.DeviceTime = new Date();
position.Latitude = loc.getLatitude();
position.Longitude = loc.getLongitude();
position.Altitude = loc.getAltitude();
position.Speed = loc.hasSpeed() ? loc.getSpeed() * 2.23693629 : 0;
position.Accuracy = (int)loc.getAccuracy();
position.Bearing = loc.hasBearing() ? loc.getBearing() : 0;
// There was cases with speed reported 1000+. Just make it real here, round of obvious errors.
if (position.Speed > 120)
{
position.Speed = 0.0;
}
PositionData.InsertPosition(getApplicationContext(), position);
}
When using the GPS provider, Bearing is usually not updated / returned unless the device physically moves and gains speed (check getSpeed()). In practice, speed above 1m/s should produce accurate bearings. I've also found that I have had to occasionally poll and check for the last known location on the GPS provider and grab it's updated bearings to get proper readings.

Android number of satellites problem [duplicate]

I'm using a GPS provider and LocationListener.onLocationChanged(Location location) to receive location fixes.
Documentation says, that Location.getExtras() contains next key/value pair:
satellites - the number of satellites used to derive the fix
but on practice I'm getting an empty extra object - there is no any data there.
Does it means that I'm getting the A-GPS fixes and not GPS?
To get the number of satellites used by the GPS engine you need to implement android.location.GpsStatus.Listener and implement its method onGpsStatusChanged().
Example...
public void onGpsStatusChanged(int event) {
int satellites = 0;
int satellitesInFix = 0;
int timetofix = locationManager.getGpsStatus(null).getTimeToFirstFix();
Log.i(TAG, "Time to first fix = " + timetofix);
for (GpsSatellite sat : locationManager.getGpsStatus(null).getSatellites()) {
if(sat.usedInFix()) {
satellitesInFix++;
}
satellites++;
}
Log.i(TAG, satellites + " Used In Last Fix ("+satellitesInFix+")");
}
I use Location.getExtras().getInt("satellites"), and it give the number of satellites in use.
Since Android API 24 GpsStatus is deprecated and one should use GnssStatus. Let us have an activity or a service processing Gps data and a LocationManager already created.
private GnssStatus.Callback gnssCallback;
public void initCallbacks() {
....
gnssCallback = new GnssStatus.Callback() {
#Override
public void onSatelliteStatusChanged(#NonNull GnssStatus status) {
final int satelliteCount = status.getSatelliteCount();
int usedCount = 0;
for (int i = 0; i < satelliteCount; ++i)
if (status.usedInFix(i))
++usedCount;
Log.d("MyServiceTag", "satellites count = " + satelliteCount + ", used = " + usedCount);
}
};
locationManager.registerGnssStatusCallback(gnssCallback, new Handler(Looper.myLooper()));
....
}
public void deinitCallbacks() {
....
locationManager.unregisterGnssStatusCallback(gnssCallback);
....
}
initCallbacks() should be called after locationManager initialization. deinitCallbacks() should be called when information on the number of satellites is no longer needed, e.g. in onDestroy(). GnssStatus.getSatelliteCount() returns total number of known satellites, GnssStatus.usedInFix(int i) tells whether i-th satellite had been used in the most actual location capture.
Nope it means that your phone manufacturer decided not to implement this. (Or you could be using the NETWORK_PROVIDER which does not use satellites)
Use a NmeaListener and parse the sentences to know the number of satellites visible or used.

Getting the number of satellites from Location object

I'm using a GPS provider and LocationListener.onLocationChanged(Location location) to receive location fixes.
Documentation says, that Location.getExtras() contains next key/value pair:
satellites - the number of satellites used to derive the fix
but on practice I'm getting an empty extra object - there is no any data there.
Does it means that I'm getting the A-GPS fixes and not GPS?
To get the number of satellites used by the GPS engine you need to implement android.location.GpsStatus.Listener and implement its method onGpsStatusChanged().
Example...
public void onGpsStatusChanged(int event) {
int satellites = 0;
int satellitesInFix = 0;
int timetofix = locationManager.getGpsStatus(null).getTimeToFirstFix();
Log.i(TAG, "Time to first fix = " + timetofix);
for (GpsSatellite sat : locationManager.getGpsStatus(null).getSatellites()) {
if(sat.usedInFix()) {
satellitesInFix++;
}
satellites++;
}
Log.i(TAG, satellites + " Used In Last Fix ("+satellitesInFix+")");
}
I use Location.getExtras().getInt("satellites"), and it give the number of satellites in use.
Since Android API 24 GpsStatus is deprecated and one should use GnssStatus. Let us have an activity or a service processing Gps data and a LocationManager already created.
private GnssStatus.Callback gnssCallback;
public void initCallbacks() {
....
gnssCallback = new GnssStatus.Callback() {
#Override
public void onSatelliteStatusChanged(#NonNull GnssStatus status) {
final int satelliteCount = status.getSatelliteCount();
int usedCount = 0;
for (int i = 0; i < satelliteCount; ++i)
if (status.usedInFix(i))
++usedCount;
Log.d("MyServiceTag", "satellites count = " + satelliteCount + ", used = " + usedCount);
}
};
locationManager.registerGnssStatusCallback(gnssCallback, new Handler(Looper.myLooper()));
....
}
public void deinitCallbacks() {
....
locationManager.unregisterGnssStatusCallback(gnssCallback);
....
}
initCallbacks() should be called after locationManager initialization. deinitCallbacks() should be called when information on the number of satellites is no longer needed, e.g. in onDestroy(). GnssStatus.getSatelliteCount() returns total number of known satellites, GnssStatus.usedInFix(int i) tells whether i-th satellite had been used in the most actual location capture.
Nope it means that your phone manufacturer decided not to implement this. (Or you could be using the NETWORK_PROVIDER which does not use satellites)
Use a NmeaListener and parse the sentences to know the number of satellites visible or used.

Categories

Resources