You are here

function gmap_polyutil_point_line_dist in GMap Module 6

Same name and namespace in other branches
  1. 5 gmap_polyutil.inc \gmap_polyutil_point_line_dist()
  2. 6.2 gmap_polyutil.inc \gmap_polyutil_point_line_dist()
  3. 7.2 gmap_polyutil.inc \gmap_polyutil_point_line_dist()
  4. 7 gmap_polyutil.inc \gmap_polyutil_point_line_dist()

Distance between a point and a line segment.

Parameters

$q: Point to measure.

$p1: Start point of line segment.

$p2: End point of line segment.

1 call to gmap_polyutil_point_line_dist()
gmap_polyutil_dp_encode in ./gmap_polyutil.inc
Implementation of the Douglas-Peucker polyline simplification algorithm. See: http://facstaff.unca.edu/mcmcclur/GoogleMaps/EncodePolyline/algorithm.html

File

./gmap_polyutil.inc, line 67
Encoded polyline utilities.

Code

function gmap_polyutil_point_line_dist($q, $p1, $p2) {
  if ($p1[0] == $p2[0] && $p1[1] == $p2[1]) {

    // lp1 and lp2 are the same point--they don't define a line--so we return
    // the distance between two points.
    return gmap_polyutil_dist($q, $p1);
  }

  // Use the dot product to find where q lies with respect to the line segment
  // p1p2. For more information, see:
  //   http://local.wasp.uwa.edu.au/~pbourke/geometry/pointline/
  //   http://www.codeguru.com/forum/printthread.php?t=194400
  $u = (($p2[1] - $p1[1]) * ($q[1] - $p1[1]) + ($p2[0] - $p1[0]) * ($q[0] - $p1[0])) / (pow($p2[1] - $p1[1], 2) + pow($p2[0] - $p1[0], 2));
  if ($u <= 0) {

    // point is not alongside segment, it is further off in $p1's direction
    return gmap_polyutil_dist($q, $p1);
  }
  elseif ($u >= 1) {

    // point is not alongside segment, it is further off in $p2's direction
    return gmap_polyutil_dist($q, $p2);
  }
  else {

    // point is alongside segment
    // calculate distance between q and the nearest point on the line segment
    // use $u to calculate the nearest point on the line segment:
    //   p1 + u*(p2 - p1) => [p1x + u*(p2x - p1x), p1y + u*(p2y - p1y)]
    return gmap_polyutil_dist($q, array(
      $p1[0] + $u * ($p2[0] - $p1[0]),
      $p1[1] + $u * ($p2[1] - $p1[1]),
    ));
  }
}