20

I want to get angle between 3 points in JavaScript.

If I have points A(x1,y1), B(x2, y2) and C(x3, y3), I want to get angle that is formed with lines AB and BC.

let A = {x:x1, y:y1}, B = {x:x2, y:y2}, C = {x:x3, y:y3}
Azametzin
  • 5,223
  • 12
  • 28
  • 46
DejanG
  • 525
  • 1
  • 10
  • 17
  • The second question *whether there is a difference in angle if these points are geographic coordinates* is off-topic to this question but can be asked as another question with tag `compass-geolocation`. I try to edit and get this highly interesting question on topic again as there already are an answer that worked for me (detecting figures). –  Oct 31 '19 at 13:02

1 Answers1

39

Try this function :

 /*
 * Calculates the angle ABC (in radians) 
 *
 * A first point, ex: {x: 0, y: 0}
 * C second point
 * B center point
 */
function find_angle(A,B,C) {
    var AB = Math.sqrt(Math.pow(B.x-A.x,2)+ Math.pow(B.y-A.y,2));    
    var BC = Math.sqrt(Math.pow(B.x-C.x,2)+ Math.pow(B.y-C.y,2)); 
    var AC = Math.sqrt(Math.pow(C.x-A.x,2)+ Math.pow(C.y-A.y,2));
    return Math.acos((BC*BC+AB*AB-AC*AC)/(2*BC*AB));
}
Walter Stabosz
  • 7,447
  • 5
  • 43
  • 75
Imane Fateh
  • 2,418
  • 3
  • 19
  • 23
  • How to use this function? Any examples? Do i have to pass Arrays as parameter?! – Black Mar 31 '16 at 13:03
  • 1
    @EdwardBlack if you look at the code, the points are passed in as an object with the form `{x: 0, y: 0}` . I edited the answer to reflect this. – Walter Stabosz May 11 '16 at 04:02
  • 12
    to convert to degree `(find_angle(A,B,C) * 180) / Math.PI` – Claudio Santos Sep 21 '16 at 21:29
  • 7
    This only provides measurements for non-reflex angles, i.e. for angles less than 180 degrees. Thus it does not distinguish between angle ABC and angle CBA. Thus the return result provides no sense of angle "direction". Depending on what the user is looking for, this may or may not be acceptable. – Andrew Willems Mar 20 '17 at 12:34
  • 1
    What if the angle is more than 180 degrees? – bumbeishvili Aug 04 '20 at 05:32
  • find_angle({x:4057.48,y:684.39},{x:4067.49,y:684.39},{x:4272.04,y:684.39}) will get a NaN result. – Fei Sun Feb 24 '22 at 02:40