Question

I am trying to calculate at what degree a pin is to the user's location. So if the pin is directly below the user's location, it would be 180 degrees. Directly to the right would be 90. There could be one between those at 154 degrees. 0 degrees is 0 degrees north of the user's location. Directly south is 180 degrees.

I've been having trouble calculating this and I wanted to know if this is even possible? Any ideas would be greatly appreciated!

Was it helpful?

Solution

Let's assume you have two points, both consisting of Latitude and Longitude, or X, Y. Assuming the user is facing north, this could be done as follows:

//Make sure you import math.h

CGPoint currentLocation = CGPointMake(100.2, 55.53);
CGPoint pin = CGPointMake(125.54, 40.23);

//Shift the 2D space to have the currentLocation as the origin
pin.x -= currentLocation.x;
pin.y -= currentLocation.y;

//Calculate the inverse tangent (in radians)
float rad = atan(pin.y/pin.x);

//Convert the radians to degrees
float deg = rad * 180/M_PI;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top