Search code examples
javascriptlineintersectionequationangle

Convert equations of lines solution into reusable javascript function with unknown x and y


So I have a solution to solving for location (point of intersection) of someone based on landmark angles (312.27) and (19.65) degrees and grid coordinates (1,5) and (9,7) of those landmarks. So the issue I'm having is how can I convert these formulas into something that I can dynamically plugin angles and grid coordinates and return the x and y intersection point for location?

Equations of the Lines based on land marks:
P1: y = cot(312.27)*x + 5 - cot(312.27)*1 ⇒ y = -0.91x + 5.91
P2: y = cot(19.65)*x + 7 - cot(19.65) * 9 ⇒ y = 2.80x - 18.21

solve point of intersection:
P1 = P2
-0.91x + 5.91 = 2.80x - 18.21
5.91 + 18.21 = 2.80x + 0.91x
24.12 = 3.71x
6.5 = x
y = -0.91(6.5) + 5.91
y = 0
Your position is (6.5,0).

So I'm looking at creating a function like:

function getLocation(angle1, angle2, coord1, coord2){}

but I just am having trouble trying to figure out how I can convert this solution into something that would output x and y. As I would have to pass around x or y which is unknown.

Any ideas would be appreciated.

note: angles are converted to radians.


Solution

  • You need to solve the system of equations in terms of the angles and the x,y coordinates:

    // let phi1 be the first angle and phi2 be the second angle thus
    // let P1 be the first point and P2 be the second point
    
    y = x * cot(phi1) + P1.y - P1.x * cot(phi1)
    
    Similarly
    
    y = x * cot(phi2) + P2.y - P2.x * cot(phi2)
    
    Equating both sides:
    
    x * cot(phi1) + P1.y - P1.x * cot(phi1) = x * cot(phi2) + P2.y - P2.x * cot(phi2)
    
    Solving for x
    
    x * (cot(phi1) - cot(phi2)) = P2.y - P2.x * cot(phi2) - P1.y + P1.x * cot(phi1)
    
    Thus:
    
    x = (P2.y - P2.x * cot(phi2) - P1.y + P1.x * cot(phi1)) / (cot(phi1) - cot(phi2)) 
    
    Once you get x you can plug x in any of the equations for y:
    
    y = x * cot(phi1) + P1.y - P1.x * cot(phi1)
    

    So to get x and y:

    function getLocation(angle1, angle2, coord1, coord2) {
    
        let num = coord2.y - coord2.x * cot(angle2) - coord1.y + coord1.x * cot(angle1)
        let den = cot(angle1) - cot(angle2)
        let x = num / den
        let y = x * cot(angle1) + P1.y - P1.x * cot(angle1)
    
        // do something awesome with x and y
    }