Question

I'm making an iPhone app for myself and colleagues for locating our devices. It involves an compass that points to the north, and an needle that points to an given coordinate of an device.

However I'm having trouble with pointing the needle to the device. I'm using the following code to try and create an 'triangle' and calculate the 'amount of radians' from the give North of the compass, so I can rotate the needle from the north to 'amount' offset from triangleC.

triangleA = curLocation.coordinate.latitude - setLocation.coordinate.latitude;
if(triangleA < 0) { east = NO; } else { east = YES; }
triangleB = curLocation.coordinate.longitude - setLocation.coordinate.longitude;
if(triangleB < 0) { north = NO; } else { north = YES; }

float tempC = pow(fabs(triangleA),2) + pow(fabs(triangleB),2);

triangleC = sqrtf(tempC);

However the triangleC does not contain an 'radians' between -360 and 360.

Together with this I have another question. Is there any private framework for getting current location of the user? Because the normal locationManager has a pretty big offset of min. 5 meters.

I hope someone can point me in the right direction for getting the right 'radians' from the north.

Was it helpful?

Solution

Instead of using the pythagorean theorem you can use trig. First get the difference between the x and y of your points

float x = curLocation.coordinate.latitude - setLocation.coordinate.latitude;
float y = curLocation.coordinate.longitude - setLocation.coordinate.longitude;

Then use arctangent to get the angle.

float angle = atan2(y,x);

If you want all positve values, add this line:

if(angle<0) angle += 2.0*M_PI;

Then if you want to use degrees (0-360) instead of radians, convert using this line:

angle = angle * (180/M_PI);   

And for your booleans. You will be pointing east when the angle is greater than 270° or less than 90°. You will be pointing north when the angle is between 0° and 180°.

east = (angle >= 270) || (angle <= 90);
north = (angle >= 0) && (angle <= 180);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top