Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS : Get angle to geolocation from current location without map

I'm working on some iPhone app and I want to make a bearing, an image that move to a specific geo location, depending on user location using accelerometer.

I read many answers here but didn't get a solution.

I have the current location coordinates and destination ones.

Have you any idea or sample code? Thanks.

like image 829
hafedh Avatar asked May 23 '12 11:05

hafedh


People also ask

How can I get the current location of a user?

To get the coordinates, all you have to do is to invoke getCurrentPosition() method on the geolocation object. This method will take a few arguments. In this case, I have two callback functions as arguments. When running the code above, the user will be prompted, asking permission to access his/her location.


1 Answers

on Top define this

#define RadiansToDegrees(radians)(radians * 180.0/M_PI)
#define DegreesToRadians(degrees)(degrees * M_PI / 180.0)

define variable in .h file

float GeoAngle;

in your location manager's delegate method :-

-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation 
{
    GeoAngle = [self setLatLonForDistanceAndAngle:newLocation];
}

And the function will be as follows:-

-(float)setLatLonForDistanceAndAngle:(CLLocation *)userlocation
{
    float lat1 = DegreesToRadians(userlocation.coordinate.latitude);
    float lon1 = DegreesToRadians(userlocation.coordinate.longitude);

    float lat2 = DegreesToRadians(locLat);
    float lon2 = DegreesToRadians(locLon);

    float dLon = lon2 - lon1;

    float y = sin(dLon) * cos(lat2);
    float x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dLon);
    float radiansBearing = atan2(y, x);
    if(radiansBearing < 0.0)
    {
        radiansBearing += 2*M_PI;
    }

    return radiansBearing;
}

You will get constantly updated angle in GeoAngle variable. to rotate the arrow to destination location take the image of arrow and assign it to IBOutlet of arrowImageView and rotate this on heading update method.

- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading 
{
    float direction = -newHeading.trueHeading;

    arrowImageView.transform=CGAffineTransformMakeRotation((direction* M_PI / 180)+ GeoAngle);
}
like image 132
Dhaval Panchal Avatar answered Oct 03 '22 00:10

Dhaval Panchal