I am creating an app that will point a simple arrow in the direction of a GPS coordinate I have plotted out. So I am talking my current location lat and long, so lat1, lon1 is the current location... then comparing them against a static coordinate of lat and long called lat2, lon2.
I have spent HOURS researching and testing, but I keep on getting the same problem. It's very aggravating. As soon as I start to drive towards my destination the arrow is all out of whacked when using the iPhone's built in GPS/compass. It will sometimes show the arrow the complete opposite side of where it needs to be, hanging to the right... pretty much nothing that is solid.
Here is the current code I am running
cpLocLat = 43.026629;
cpLocLon = -78.867188;
Those are float values and the coordinates of where I want to drive to.
float lat1 = self.locManager.location.coordinate.latitude;
float lat2 = cpLocLat;
float lon1 = self.locManager.location.coordinate.longitude;
float lon2 = cpLocLon;
float heading = atan2(sin(lon2 - lon1) * cos(lat2), cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(lon2 - lon1));
heading = RADIANS_TO_DEGREES(heading);
if (heading < 0) {
heading = heading + 360;
}
I use this function every time the locationManager didUpdateToLocation delagate is called. Once I have that information, it is used in the locationManager didUpdateHeading delagte with the following:
CGAffineTransform where = CGAffineTransformMakeRotation(degreesToRadians((degrees - newHeading.magneticHeading)));
[self.compassContainer2 setTransform:where];
and here is the degressToRadians macro
#define degreesToRadians(x) (M_PI * x / 180.0)
So whenever I run this code it is failing epically and is making me go nuts!
BTW - I have used the following URLs for reference
http://www.shawngrimes.me/2011/07/calculating-heading-with-corelocation/
Using Compass to point to actual coordinate location instead of just North
Point to location using compass
To my knowledge, the formula for the initial bearing according to the Haversine formula is:
θ = atan2( sin(Δlong).cos(lat2), cos(lat1).sin(lat2) − sin(lat1).cos(lat2).cos(Δlong) )
which seems to be exactly what you used. According to the man entry, you might have to use the reverse order of the two arguments to atan2:
ATAN2(3) BSD Library Functions Manual ATAN2(3)
NAME
atan2 -- arc tangent function of two variables
SYNOPSIS
....
float
atan2f(float y, float x);
So y comes before x. Maybe that is the error.
Also, make sure that the coordinate deltas (lat2-lat1 etc.) are in radians.
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