manuelbieh / geolib

Zero dependency library to provide some basic geo functions
MIT License
4.23k stars 341 forks source link

Method to calculate bearing between points #28

Closed objectiveSee closed 9 years ago

objectiveSee commented 10 years ago

I implemented a method to calculate bearing between points which could be useful. Should we add this?

// From http://www.movable-type.co.uk/scripts/latlong.html var bearingFromPoints = function (pointA, pointB) { var lat1 = pointA.latitude; var lon1 = pointA.longitude; var lat2 = pointB.latitude; var lon2 = pointB.longitude;

// var dLat = (lat2-lat1).toRad();  // unused
var dLon = (lon2-lon1).toRad();

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 brng = Math.atan2(y, x).toDeg();
return brng;

};

objectiveSee commented 10 years ago

FYI: I understand trig, but didn't put any thought into this one (I googled it). Perhaps the solution is incorrect for a curved surface like Earth.

manuelbieh commented 10 years ago

Can you send a pull request? I will have a look then ;)

Thank you!

objectiveSee commented 10 years ago

I am sure that this bearing function is incorrect, because it does not take into account the size of the Earth.

outaTiME commented 9 years ago

What about this ...

function radians(n) {
  return n * (Math.PI / 180);
}
function degrees(n) {
  return n * (180 / Math.PI);
}

function getBearing(startLat,startLong,endLat,endLong){
  startLat = radians(startLat);
  startLong = radians(startLong);
  endLat = radians(endLat);
  endLong = radians(endLong);

  var dLong = endLong - startLong;

  var dPhi = Math.log(Math.tan(endLat/2.0+Math.PI/4.0)/Math.tan(startLat/2.0+Math.PI/4.0));
  if (Math.abs(dLong) > Math.PI){
    if (dLong > 0.0)
       dLong = -(2.0 * Math.PI - dLong);
    else
       dLong = (2.0 * Math.PI + dLong);
  }

  return (degrees(Math.atan2(dLong, dPhi)) + 360.0) % 360.0;
}
outaTiME commented 9 years ago

oups, method exists in source but no documentation in readme ...

https://github.com/manuelbieh/Geolib/blob/master/src/geolib.js#L749