In my webapp, have a JSON data response from a database query that includes the lat/long coordinates of 1 to n locations. I want to calculate the bearing from the data[i]
This is an edit of the accepted answer with some modifications which made it work for me (mainly the use of toRad function on lat,lng values).
var geo = {
/**
* Calculate the bearing between two positions as a value from 0-360
*
* @param lat1 - The latitude of the first position
* @param lng1 - The longitude of the first position
* @param lat2 - The latitude of the second position
* @param lng2 - The longitude of the second position
*
* @return int - The bearing between 0 and 360
*/
bearing : function (lat1,lng1,lat2,lng2) {
var dLon = this._toRad(lng2-lng1);
var y = Math.sin(dLon) * Math.cos(this._toRad(lat2));
var x = Math.cos(this._toRad(lat1))*Math.sin(this._toRad(lat2)) - Math.sin(this._toRad(lat1))*Math.cos(this._toRad(lat2))*Math.cos(dLon);
var brng = this._toDeg(Math.atan2(y, x));
return ((brng + 360) % 360);
},
/**
* Since not all browsers implement this we have our own utility that will
* convert from degrees into radians
*
* @param deg - The degrees to be converted into radians
* @return radians
*/
_toRad : function(deg) {
return deg * Math.PI / 180;
},
/**
* Since not all browsers implement this we have our own utility that will
* convert from radians into degrees
*
* @param rad - The radians to be converted into degrees
* @return degrees
*/
_toDeg : function(rad) {
return rad * 180 / Math.PI;
},
};
/** Usage **/
var myInitialBearing = geo.bearing(0,0,45,45);
Find theory and online calculator at: http://www.movable-type.co.uk/scripts/latlong.html