One way to find if a point is in a polygon is to count how many times a line drawn from the point (in any direction) intersects with the polygon boundary. If they intersect an even number of times, then the point is outside.
I have implemented the C code from this Point in Polygon article in php and used the polygon below to illustrate.
<?php
//Point-In-Polygon Algorithm
$polySides = 4; //how many corners the polygon has
$polyX = array(4,9,11,2);//horizontal coordinates of corners
$polyY = array(10,7,2,2);//vertical coordinates of corners
$x = 3.5;
$y = 13.5;//Outside
//$y = 3.5;//Inside
function pointInPolygon($polySides,$polyX,$polyY,$x,$y) {
$j = $polySides-1 ;
$oddNodes = 0;
for ($i=0; $i<$polySides; $i++) {
if ($polyY[$i]<$y && $polyY[$j]>=$y
|| $polyY[$j]<$y && $polyY[$i]>=$y) {
if ($polyX[$i]+($y-$polyY[$i])/($polyY[$j]-$polyY[$i])*($polyX[$j]-$polyX[$i])<$x) {
$oddNodes=!$oddNodes; }}
$j=$i; }
return $oddNodes; }
if (pointInPolygon($polySides,$polyX,$polyY,$x,$y)){
echo "Is in polygon!";
}
else echo "Is not in polygon";
?>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…