gps speed compensation of location - android

I am using GPS with Android and need to have the location compensated for speed to remove the error due to the lag of the calculation of location. My speeds of interest are in the 5 to 10 mph range as this is for a sailboat.
Here is my code:
public double[] correctLocation(double pLat,double pLong,double pAngle,double pSpeed, double factor){
double[] latLong = new double[2];
latLong[0] = pLat + factor * pSpeed * Math.cos(pAngle * Math.PI / 180);
latLong[1] = pLong + factor * pSpeed * Math.sin(pAngle * Math.PI / 180) / Math.cos(pLat * Math.PI / 180);
return latLong;
}
I did a test run at 25mph in a car and calculated that the factor should be 3E-6 but in trying it out at running and walking speed it is clear that a factor more like 6E-6 is needed. I can't find any references to this through Google although I know people do this for example in the Google self driving car. I assume others do these kind of corrections.
Can anyone help me out here? The GPS is a Qstarz A1000XT with a MTK chipset. There are probable things I am missing with this simplistic approach. (I am assuming I don't need acceleration as this is a heavy boat with a 1 minute time constant for acceleration).

The 6E-6 was correct. I had a couple of errors and was confused for some time on this. I ended up testing by traveling at a spot from both directions at 25MPH and pinging the spot. I interpolated between GPS readings so that the timing and update rate were not a factor. I did this 10 times. That gave me two clusters of points and using a graphical method I adjusted the correction factor until the clusters overlapped. An alternate method is to use the difference in latitude and longitude between the last two readings, which are 1 second apart, and apply a correction factor in seconds. In my case that was 1.25 seconds. Both methods produced the same result in terms of the clusters. The speed correction was a tad closer in the scatter but not by much. Speed on GPS is measured off the carrier and not derived from differences in position and is more accurate.

Related

Android, using gps and compass to point towards coordinate

I'm trying to make an app that points you toward a position. You press a button and it stores the gps coordinates, then calculates things like distance and the angle you need to face. Then it leads you back to that remembered position by "pointing" toward it using an onscreen compass graphic.
At least, it's supposed to. After messing with the code for hours, I've come to the conclusion that there's just a logic error somewhere due to my lack of trig practice over the past few years.
The compass and GPS position are updated fairly frequently. This is the code in my main update call for the user interface that rotates the compass and displays the distance.
public void updateUI(){
double deltaX = targetLongitude - currentLongitude;
double deltaY = targetLatitude - currentLatitude;
double distance = Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));
double rotation = Math.toDegrees(Math.atan2(deltaX,deltaY));
distanceTextView.setText(Double.toString(distance));
rotateCompass(rotation - degreesClockwiseFromNorth);
}
and the code for rotateCompass:
public void rotateCompass(double degrees){
degrees -= currentRotation; //calculates necessary rotation across updates
currentRotation += degrees;
matrix.postRotate(
(float) degrees,
compass.getDrawable().getBounds().width() / 2,
compass.getDrawable().getBounds().height() / 2);
compass.setImageMatrix(matrix);
}
I'm almost certain my rotation code works because when I replace
rotateCompass(rotation - degreesClockwiseFromNorth);
with
rotateCompass(0 - degreesClockwiseFromNorth);
it points north right alongside a real compass regardless of the direction I'm facing. But when I use the former, it points towards a consistent point, but that point seems to be nowhere near the target point.
So I've come to the conclusion my error is either in calculating the correct angle, or expecting the gps to be too precise. I haven't tested it for distances further than what I can in my backyard, but I assume that if it was a gps accuracy issue I'd see my compass jumping all over the place rather than adamantly pointing in a wrong direction.
Thanks for reading, any suggestions or corrections are appreciated.
Your math is all screwed up because the distance between 2 degrees of longitude is not the same as 2 degrees of latitude. In fact, it isn't even a constant length for longitude- its shorted by the poles and longest at the equator. Use the Location.distanceTo functions instead.

Calculating Speed for a navigation app without getSpeed() method

I am developing an app which is more of a time-shift racing between your friends.
I need to calculate speed of a moving vehicle, and I don't want to use Location.getSpeed() method. (Explained in detail in the bottom why I don't want to use it)
I am trying to calculate speed with the help of Latitude and Longitude available to me, and this is where I need help.
The help needed: I would want to know is:
If the algorithm is correct
Should I calculate in Centimeters instead of meters
And if there's any code/library already available which does it.
I am using the following code:
This gives me distance between two LatLng points:
long getDistanceBetweenPoints(double lat1, double lng1, double lat2, double lng2 ){
double dLat = Math.toRadians(lat2 - lat1);
double dLon = Math.toRadians(lng2 - lng1);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
+ Math.cos(Math.toRadians(lat1))
* Math.cos(Math.toRadians(lat2)) * Math.sin(dLon / 2)
* Math.sin(dLon / 2);
double c = 2 * Math.asin(Math.sqrt(a));
long distanceInMeters = Math.round(6371000 * c);
return distanceInMeters;
}
And the following code is how it is being used:
if(lastLat == -1 && lastLng == -1){
lastLat = location.getLatitude();
lastLng = location.getLongitude();
lastTimeStamp = location.getTime();
return;
}
long distanceInMeters = getDistanceBetweenPointsAndSetTotal(lastLat, lastLng, location.getLatitude(), location.getLongitude());
long timeDelta = (location.getTime() - lastTimeStamp)/1000;
long speed = 0;
if(timeDelta > 0){
speed = (distanceInMeters/timeDelta);
}
Log.d("Calculations","Distance: "+distanceInMeters+", TimeDelta: "+timeDelta+" seconds"+",speed: "+speed+" Accuracy: "+location.getAccuracy());
lastLat = location.getLatitude();
lastLng = location.getLongitude();
lastTimeStamp = location.getTime();
When I run it, I get following output from that LogCat:
Distance: 0, TimeDelta: 0 seconds,speed: 0 Accuracy: 5.0
Detailed Reasons
The target consumers are not supposed to have high quality devices with high-quality GPS chips, thus always getting a very accurate fix when the device is on the move is not possible.
I thus don't want to depend on the Location.getSpeed() method, since I have observed it gives out speed values only when the accuracy is in the range of 5~8 metres.
The normal accuracy ranges I am getting in general circumstances is 10-15 metres, and getSpeed() doesn't give any speed. Even hasSpeed() starts returning false.
I have been tinkering my head around this thing for more than 3 days, any help in this would be deeply appreciated.
Much Thanks in Advance!
I develop MyTrails, an Android mapping and tracking app, and like you I struggled at first with the very crude location APIs Google has seen fit to include in Android.
hasSpeed() is false when the GPS chip doesn't have a good enough fix to compute speed based on dopler effect. Even when it does, I usually don't trust the speed if it's less than 5km/h or thereabouts.
The way I handle speed calculations is by using a crude low-pass filter: I record a trackpoint every second (and a minimum of 5m apart, based on LocationManager.requestLocationUpdates(), and to calculate the recent speed, I go back a few samples to get one that is a sufficient distance apart (but no more than 30s prior), and perform the averaging you're doing.
I'm using Location.distanceBetween() for the actual distance calculation. Beware that it fails on a very small (but unfortunate) number of devices, so the haversine method you have may be a better bet. You may want to check it though, what I have is
/**
* Gets distance in meters, coordinates in RADIAN
*/
private static double getDistance(double lat1, double lon1, double lat2, double lon2) {
double R = 6371000; // for haversine use R = 6372.8 km instead of 6371 km
double dLat = lat2 - lat1;
double dLon = lon2 - lon1;
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(lat1) * Math.cos(lat2) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
//double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
return 2 * R * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
// simplify haversine:
//return 2 * R * 1000 * Math.asin(Math.sqrt(a));
}
(note the 1000 factor)
I agree with Pierre, also you are rounding the results. If the points are not far enough apart, you're rounding may just provide 0. I don't see how the rounding tolerance is defined.
I always calculate in meters - it makes things much easier. I'd suggest following the SI standard units in your code.
Your output also shows that the timeDelta is zero, so no distance was actually calculated.
Omg.....
Location
Check this method - it allows you to calculate distance between 2 geo points, just divide it by your time. It should be much more accurate than yours as it calculates distances with much better approximation (WGS83 instead of using sin, cos and rest of this stuff).
Good, general idea is to keep all your data in plain units like m, s, kg etc. and make changes only for showing data to user.
If the algorithm is correct?
The distance calculation looks like the haversine formula which is correct.
(There are much faster formulas for small distances (and you only use small distances), but haversine will work)
Should I calculate in Centimeters instead of meters?
Never use centimeter, stay with SI units, the unit of speed is meter/s. just use meter as floating point (double).
Ios, where I am developping a tracking App, seems to be more friendly related to the getSpeed() nethod from Location class.
But I (again?) warn you to use speeds at slow speed. If you get an invalid speed, then just stop calculation or mark it as invalid in your app.
If the GPS chip cannot deliver a valid speed, it has good reason to do so, and it's an interesting question whether you will do it better.
At low speed GPS tends to randomly jump around the true position, giving 5-30m jumps.
It's very likely that your self calculated speed shows much more speed that the device is (not) moving.
Try to fix your app, that it does not need speeds at low speeds.

Check if device is really moving

I am working on an application where I need to get the speed of a car. To get the speed, I know I can use something like double speed =locationB.getSpeed();` however when I am testing, the speed varies between 0.0 and 40 km/h when I am just sitting right behind my laptop not moving at all. In the car, the speed actually comes close to the cars speed, so that shouldn't be a problem.
What would be the best way to check if the device is really moving? I've already tried to get the distance between locationA and locationB and use that with the time it took to get the 2 locations, to get the speed.
double distance = locationA.distanceTo(locationB);
double speed = (distance / time) * 3600 / 1000;
However this seems to be not stable at all, like the getSpeed() method.
Is there a way to only display the speed if the device is moving? And would it be reliable?
Any help is appreciated,
Thanks.
Check the horicontal accuracy attribute of Location.
If it is under 30m you can ignore the location.
If you are sitting on your laptop and get speed = 40km/h (which I never saw in good GPS devices), then look what the hor. accuracy is.
It probably is much over 30m.
In GPS based systems, never ever calculate the speed by positional change in time,
just use the location.getSpeed().
The reason is that the GPS chip internally calculates the speed via physical doppler effect, not via positional change.
While standing still, or at very low speeds this does not work well, so you have to filter out very low speeds, and bad gps signal. (via horicontal accuracy estimate)
I think you should limit the distance between A and B to be a minimum length. Small distances will introduce more error into your speed calculations.
Boolean moving - false;
double distance = locationA.distanceTo(locationB);
double speed = (distance / time) * 3600 / 1000;
if (distance > SOME_THRESHOLD) {
moving = true
}

Calculate distance between two points

I'm making an application for tracking a user as they run, cycle or walk and display it to the screen.
I know that there is distanceBetween function built into android but is this accurate enough for a fittness application?
I was considering using Haversine formula or other such formula for calculating distances between points the only problem I see about these formulas is that it usually is straight line or as the crow flys distances.
Does anyone have an idea about this?
The Haversine formula is accurate for most distances, but it suffers from rounding errors when the points are (nearly) antipodal. The following formula is accurate for all distances.
> double delta = G1 - G2;
> double p1 = cos(L2) * sin(delta);
> double p2 = cos(L1) * sin(L2) - sin(L1) * cos(L2) * cos(delta);
> double p3 = sin(L1) * sin(L2) + cos(L1) * cos(L2) * cos(delta);
> distance = 60 * Math.atan2(Math.sqrt(p1*p1 + p2*p2), p3);
Here's an example and the implementation.
resource : Here
Tracking their route as they walk is going to involve a series of way points. If you sample at say 1 way point every 10 seconds then you can calculate the distance between the previous point and the new point using either a crow-flys technique like haversine or just make some webservice requests to an external service like google maps and their distance matrix which can give you the snapped-to-streets distance between 2 points using suggested best path.
http://code.google.com/apis/maps/documentation/distancematrix/
You just have to make sure that your sample rate isn't too high or you can go over the 2500 API calls/24-hour-period rate limiter (which is per IP I believe). But 2500 will give you 7 hours at 1 sample per 10 seconds, or you can try a lower rate like 1 per 35 seconds and risk having the route be guessed wrong, but guarantee that your device won't go over 2500 samples.
Personally, if location polling is free, I would just go with distanceBetween and poll every 1-2 seconds. That should be short enough that the accuracy of GPS becomes your biggest source of error.

Calculating speed from 2 points

I know this question has been asked a lot, but not yet to my satisfaction. I am trying to use the GPS of an Android device to calculate speed. A lot of people seem to reply by saying to simply use the getSpeed() function of the Location object. From what I understand though, getSpeed() will only work on certain devices that have a speed sensor built into the GPS receiver chip. I want my application to work regardless of this, so I am using the following haversine formula:
private double CalculateHaversineMI(double lat1, double long1, double lat2,double long2) {
double dlong = (long2 - long1) * (Math.PI / 180.0f);
double dlat = (lat2 - lat1) * (Math.PI / 180.0f);
double a = Math.pow(Math.sin(dlat / 2.0), 2)
+ Math.cos(lat1 * (Math.PI / 180.0f))
* Math.cos(lat2 * (Math.PI / 180.0f))
* Math.pow(Math.sin(dlong / 2.0), 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double d = 3956 * c;
return d;
}
Now what I'm trying to do is figure out how to calculate speed from this. Can anyone help me please?
What I can see is that your function returns correct path distance between 2 points on a sphere - it is d. But, this formula is needed only if you have 2 points on a sphere that are not close to each other (means central angle of their separation is not small, central angle of 1 degree corresponds to distance of 111 km approx, just to get feeling). If they are close to each other (which is the case for people moving and slow speed vehicles), then you do not need this formula. You can simply and very accurately approximate arc on the sphere with the straight line, and then calculation becomes trivial.
Sample GPS position at regular time periods. Calculate distance from the last position obtained. For that purpose you may use distanceTo() function from android.location.Location.
Calculate speed by dividing distance with time elapsed between 2 measurements.
Average calculated speeds for more accurate results, but ensure that you do not lose sensitivity to speed changes. So, you would need some trade-off on number of samples averaged.
That calculates the distance. Now as you may recall, speed = distance / time, so somewhere along the line you need to capture the time as well as the position.
On another note, the formula that you are using is way OTT for what you are trying to do. You would be better off making a number of approximations based on the fact that the path you are traversing is much less than the circumference of the earth. Then you could arrive at a much simpler formula.

Categories

Resources