title: Calculating bearing between two CLLocationCoordinate2Ds
body: <p>Very "simple" problem: given two CLLocationCoordinate2Ds, how can I get the bearing (as radians) from the first to the second? I've done a lot of research and studying on this, both the general problem and Objective-C/Cocoa Touch/iOS specifically.</p>
  
  <p>Here's my implementation:</p>
  
  <pre><code>- (float) getHeadingForDirectionFromCoordinate:(CLLocationCoordinate2D)fromLoc toCoordinate:(CLLocationCoordinate2D)toLoc
  {
      float fLat = fromLoc.latitude;
      float fLng = fromLoc.longitude;
      float tLat = toLoc.latitude;
      float tLng = toLoc.longitude;
  
      return atan2(sin(fLng-tLng)*cos(tLat), cos(fLat)*sin(tLat)-sin(fLat)*cos(tLat)*cos(fLng-tLng));         
  }
  </code></pre>
  
  <p>However, this method isn't returning consistant results for me.  If the bearing is close to due north or due south, it seems to be fine, however, any other direction seems to return inconsistant data, for example:</p>
  
  <p>From 50.405018, 8.437500</p>
  
  <p>To 51.339802, 12.403340</p>
  
  <p>My method returns: 5.918441 radians</p>
  
  <p>Should be 1.18660576 radians </p>
  
  <p>(see <a href="http://www.movable-type.co.uk/scripts/latlong.html" rel="nofollow noreferrer">http://www.movable-type.co.uk/scripts/latlong.html</a> and <a href="http://www.movable-type.co.uk/scripts/latlong-map.html?lat1=50.405018&amp;long1=8.437500&amp;lat2=51.339802&amp;long2=12.403340" rel="nofollow noreferrer">http://www.movable-type.co.uk/scripts/latlong-map.html?lat1=50.405018&amp;long1=8.437500&amp;lat2=51.339802&amp;long2=12.403340</a>)</p>
  
  <p>I've double and triple checked the formula is correct. I've also spot checked a bunch of values like the example above, some correct, some wrong.  I've played around with various modulos or bounding of the return value, also no luck.</p>
  
  <p>Any ideas? Is there an issue with my code? Maybe I've misunderstood something about how math functions work?</p>