Location\Polygon::contains PHP Method

contains() public method

Determine if given point is contained inside the polygon. Uses the PNPOLY algorithm by W. Randolph Franklin. Therfore some edge cases may not give the expected results, e. g. if the point resides on the polygon boundary.
See also: http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html For special cases this calculation leads to wrong results: - if the polygons spans over the longitude boundaries at 180/-180 degrees
public contains ( Coordinate $point ) : boolean
$point Coordinate
return boolean
    public function contains(Coordinate $point)
    {
        $numberOfPoints = $this->getNumberOfPoints();
        $polygonLats = $this->getLats();
        $polygonLngs = $this->getLngs();
        $polygonContainsPoint = false;
        for ($node = 0, $altNode = $numberOfPoints - 1; $node < $numberOfPoints; $altNode = $node++) {
            if ($polygonLngs[$node] > $point->getLng() != $polygonLngs[$altNode] > $point->getLng() && $point->getLat() < ($polygonLats[$altNode] - $polygonLats[$node]) * ($point->getLng() - $polygonLngs[$node]) / ($polygonLngs[$altNode] - $polygonLngs[$node]) + $polygonLats[$node]) {
                $polygonContainsPoint = !$polygonContainsPoint;
            }
        }
        return $polygonContainsPoint;
    }

Usage Example

Beispiel #1
0
 public function testIfNotContainsPointCheckWithWorksAsExpected()
 {
     $polygon = new Polygon();
     $polygon->addPoint(new Coordinate(10, 20));
     $polygon->addPoint(new Coordinate(10, 40));
     $polygon->addPoint(new Coordinate(30, 40));
     $polygon->addPoint(new Coordinate(30, 20));
     $point = new Coordinate(20, 10);
     $this->assertFalse($polygon->contains($point));
     $point = new Coordinate(20, 50);
     $this->assertFalse($polygon->contains($point));
     $point = new Coordinate(0, 30);
     $this->assertFalse($polygon->contains($point));
     $point = new Coordinate(40, 30);
     $this->assertFalse($polygon->contains($point));
 }