6

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.

Paul R
  • 208,748
  • 37
  • 389
  • 560
hafedh
  • 539
  • 1
  • 9
  • 26
  • See [this](http://stackoverflow.com/questions/6745131/how-can-we-find-the-angle-between-two-locations-defined-by-latitude-or-longitude) and [this](http://www.movable-type.co.uk/scripts/latlong.html) for Reference – Mehul Mistri May 23 '12 at 11:41

1 Answers1

12

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);
}
Dhaval Panchal
  • 2,529
  • 1
  • 25
  • 36
  • THank you I get the angle, but how to rotate correctly my image using accelerometer to show this direction? I'm used the angle in this method : -(void) accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration; but it still not updating even I rotate the iPhone. – hafedh May 23 '12 at 14:07
  • If you want to point the arrow to destination location then check the answer again I edited the answer. – Dhaval Panchal May 24 '12 at 05:15
  • Thank you, because of this code now I can rotate my map, based on locations – Arpit B Parekh Jan 25 '22 at 07:12