Thursday, November 24, 2011

PHP Function that Calculates Distance Between a Line and a Point

Here is a brief PHP function that calculates the distance between a line and a point. I had trouble finding a good example online so I decided to create my own:
/**
 * Copyright (c) 2011, Geoffrey Cox
 * You are granted unlimited rights to this code.
 * Finds the distance from a point (px, py) to a line that
 * passes through points ($x1, $y1) and ($x2, $y2).
 * Based on logic found at
 * http://www.worsleyschool.net/science/files/...
 * linepoint/method5.html
 */
function distanceFromLine($px, $py, $x1, $y1, $x2, $y2)
{
    $ad = $x2 - $x1;
    if ($ad == 0)
        return abs($px - $x1);
    $a = ($y2 - $y1)/$ad;
    $c = $y1 - $a*$x1;
    return abs($py - $c - $a*$px)/sqrt($a*$a + 1);
}

No comments:

Post a Comment