You are here

public function GmapPolylineToolbox::getPointLineDist in GMap Module 7.2

Distance between a point and a line segment.

former gmap_polyutil_point_line_dist()

Return value

float Distance.

File

lib/Drupal/gmap/GmapPolylineToolbox.php, line 194
Contains GmapPolylineToolbox.php Encoded polyline utilities.

Class

GmapPolylineToolbox

Namespace

Drupal\gmap

Code

public function getPointLineDist() {
  if ($this->startPoint[0] == $this->endPoint[0] && $this->startPoint[1] == $this->endPoint[1]) {

    // lp1 and lp2 are the same point--they don't define a line--so we return
    // the distance between two points.
    return $this
      ->setLinePoints($this->measurePoint, $this->startPoint)
      ->getDist();
  }

  // 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 = (($this->endPoint[1] - $this->startPoint[1]) * ($this->measurePoint[1] - $this->startPoint[1]) + ($this->endPoint[0] - $this->startPoint[0]) * ($this->measurePoint[0] - $this->startPoint[0])) / (pow($this->endPoint[1] - $this->startPoint[1], 2) + pow($this->endPoint[0] - $this->startPoint[0], 2));

  // Point is not alongside segment, it is further off in $p1's direction.
  if ($u <= 0) {
    return $this
      ->setLinePoints($this->measurePoint, $this->startPoint)
      ->getDist();
  }
  elseif ($u >= 1) {
    return $this
      ->setLinePoints($this->measurePoint, $this->endPoint)
      ->getDist();
  }
  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 $this
      ->setLinePoints($this->measurePoint, array(
      $this->startPoint[0] + $u * ($this->endPoint[0] - $this->startPoint[0]),
      $this->startPoint[1] + $u * ($this->endPoint[1] - $this->startPoint[1]),
    ))
      ->getDist();
  }
}