Search code examples
javascriptgeometrycoordinatesangle

javascript angle between two coordinates atan and atan2


I am working with an array of objects. Each array records the new X, newY, oldX, oldY.

From this, I am trying to calculate the angle between each new coordinate following the theory using Math.atan() and Math.atan2(). But they seem to produce different results and I am not sure which one should I use.

const allCoOrdinate = [{
    "newX": 455.845577,
    "newY": 383.3440431,
    "oldX": 460.8,
    "oldY": 360
}, {
    "newX": 500.2485855,
    "newY": 444.4595412,
    "oldX": 537.6,
    "oldY": 360
}, {
    "newX": 500.2485855,
    "newY": 520.0024514,
    "oldX": 614.4,
    "oldY": 360
}, {
    "newX": 455.845577,
    "newY": 581.1179495,
    "oldX": 691.2,
    "oldY": 360
}, {
    "newX": 384,
    "newY": 604.4619926,
    "oldX": 768,
    "oldY": 360
}, {
    "newX": 312.154423,
    "newY": 581.1179495,
    "oldX": 844.8,
    "oldY": 360
}, {
    "newX": 267.7514145,
    "newY": 520.0024514,
    "oldX": 921.6,
    "oldY": 360
}, {
    "newX": 267.7514145,
    "newY": 444.4595412,
    "oldX": 998.4,
    "oldY": 360
}, {
    "newX": 312.154423,
    "newY": 383.3440431,
    "oldX": 1075.2,
    "oldY": 360
}, {
    "newX": 384,
    "newY": 360,
    "oldX": 1152,
    "oldY": 360
}];

allCoOrdinate.map((a) => {
    const diffY = a.newY - a.oldY;
    const diffX = a.newX - a.oldX;
    const angleAtan = Math.atan(diffY / diffX) * (180 / Math.PI);
    const angleAtan2 = Math.atan2(diffY, diffX) * (180 / Math.PI);
    a.diffY = diffY, a.diffX = diffX, a.angleAtan = angleAtan, a.angleAtan2 = angleAtan2;
})

console.log(allCoOrdinate);
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>    
    <div id="container" class="svg-container"></div>
    <svg>
      
    </svg>
    
</body>

</html>

Excel produces this.

I want the output in javascript but am extremely confused about what syntax should I use to get accurate results.

enter image description here


Solution

  • atan function gives value in range -Pi/2..Pi/2 (-90..90 degrees), while atan2 is intended for full circle range -Pi..Pi (look at specifications in Math description).

    You can see that you result difference is exactly 180=Pi for cases when angle is in the second and third quarters.

    So results are correct, and you just have to interpret them properly. For vectors (direction!) we need angle in full range, while line might be described with half-range angle value provided by atan