Great Circle Bearing Code

Greetings!

I am currently trying to code a function that when given two GPS coordinates, it will return the Great Circle Bearing needed to get from Point A to Point B. The current code for my test coordinates returns 41degrees, when most other websites confirm the bearing to be around 154 degrees.

I am wondering if someone could help me with my code. Thanks!

float bearingCalc;
  flon1 = 38.430767 * (PI/180);
  flat1 = -122.756332 * (PI/180);
  flon2 = 38.231410 * (PI/180);
  flat2 = -122.634388 * (PI/180);
  
  float dlat = (flat2 - flat1);
  float dlon = (flon2 - flon1);
  float y = sin(dlon)*cos(flat2);
  float x = (cos(flat1)*sin(flat2)) - (sin(flat1)*cos(flat2)*cos(dlon));
  
  bearingCalc = atan2 (y,x);

  bearingCalc = bearingCalc * (180/PI);
  if(bearingCalc<=0){
    bearingCalc=360-bearingCalc; 
  }
  
  Serial.println(bearingCalc);
  return bearingCalc;

I don't recognise that as the haversine formula but I haven't tried to follow your calculation through to see whether I believe it. However, this part at the end caught my eye:

  if(bearingCalc<=0){
    bearingCalc=360-bearingCalc; 
  }

I guess you're trying to normalise the bearing, but that's not what this does.

Lots of A few subjects started on this matter lately.

(I wonder...)

(I wonder...)

Hmmm. Coincidence? :slight_smile:

Anyway:
@OP

  flon1 = 38.430767 * (PI/180);
  flat1 = -122.756332 * (PI/180);
  flon2 = 38.231410 * (PI/180);
  flat2 = -122.634388 * (PI/180);

These aren't right. You've got the lats and longs mixed up. latitudes can't be -122!

Pete

el_supremo:

(I wonder...)

Hmmm. Coincidence? :slight_smile:

Anyway:
@OP

  flon1 = 38.430767 * (PI/180);

flat1 = -122.756332 * (PI/180);
  flon2 = 38.231410 * (PI/180);
  flat2 = -122.634388 * (PI/180);



These aren't right. You've got the lats and longs mixed up. latitudes can't be -122!

Pete

Wow, I didn't notice that at all. That appears to have fixed my bearing problem.

Thank you for your help!