Search code examples
phpgeometrycartesiancartesian-coordinates

Perpendicular Distance from a Point to a line represented by two points


I have a point C(Cx,Cy) and then a line represented by two points A(Ax,Ay) and B(Bx,By). I need to find the perpendicular distance between the point C and the line represented by AB. How do I do this in PHP?


Solution

  • The answer is straight forward.Its mathematics rather than PHP

    <?php
        //Coordinates are (a,b) and (c,d)
        //the point (x,y) is the required point.
        $a=1;
        $b=2;
        $c=3;
        $d=4;
    
        $m=($d-$b)/($c-$a);
        //echo $m."\n";
    
        $x=10;
        $y=20;
        //echo $y-($m*$x)-$b+($m*$a)."\n";
        $distance=abs($y-($m*$x)-$b+($m*$a))/sqrt(1+($m*$m));
        echo $distance;
       ?>