Your final line in bearing
serves to change the direction of the bearing from clockwise to anticlockwise.
You should just use
return (brng + 360) % 360;
In addition, you do realise that you're using hard-coded values in calculateArrowRotation()
and that the input parameter location
is never used, right?
Finally, your implementation of bearing is incorrect. That's not your fault though, the sites that list the implementations can be hazy on one important detail: Everything that you feed into the trig functions must have been converted to radians first:
function bearing(lat1,lng1,lat2,lng2) {
var dLon = toRad(lng2-lng1);
lat1 = toRad(lat1);
lat2 = toRad(lat2);
var y = Math.sin(dLon) * Math.cos(lat2);
var x = Math.cos(lat1)*Math.sin(lat2) - Math.sin(lat1)*Math.cos(lat2)*Math.cos(dLon);
var rad = Math.atan2(y, x);
var brng = toDeg(rad);
return (brng + 360) % 360;
}