Search code examples
iphoneiosios4

Angle to Mecca from current location with iPhone compass


I have a question about the Qibla direction, I am building an iPhone application which will show both North direction and Qibla direction, I am showing the north direction with the help of CLLocationManager and updating it with CLHeading as newHeading.magneticHeading, And i am showing the Qibla direction with the following code

double A = MECCA_LONGITUDE - lon;
double b = 90.0 - lat;
double c = 90.0 - MECCA_LATITUDE;
NSLog(@"tan -1( sin(%f) / ( sin(%f) * cot(%f) - cos(%f) * cos(%f)))", A, b, c, b, A);
double qibAngle =  atan(sin(A) /( sin(b) * (1 / tan(c)) - cos(b) * cos(A) ));
NSLog(@"qib Angle- %f",qibAngle);
qibla.transform = CGAffineTransformMakeRotation(qibAngle * M_PI /180);

So, here i am getting the angle, but it does not update the angle when i rotate the device, Can anyone help me out, i know that i need to do some thing with heading , but i don't know what to do?


Solution

  • I assume the code you posted computes the angle between geographical north and the direction towards Mecca for the current location. All you need to do now is take into account the user's heading.

    For example, suppose the user is located so Mecca is directly due West, and the user is facing directly due East. Since tan returns +/-90 degrees, the qibla angle would have to be -90 degrees. Now the adjustment should be obvious: you need to subtract 90 degrees from the qibla angle respective to geographical north (-90) to arrive at (-180) degrees, which is how much user needs to turn in order to face Mecca.

    Simply put, you need to "undo" the user's deviation, and you do this by subtracting from the qibla angle the the user's heading, which is relative to geographical north.

    With the maths out of the way, now you need to observe heading changes and recompute the qibla angle when the heading changes. Lastly, make sure to use the trueHeading property.