Home  >  Article  >  Database  >  How can we determine if a point lies within a polygon using PHP?

How can we determine if a point lies within a polygon using PHP?

DDD
DDDOriginal
2024-10-25 03:38:02696browse

How can we determine if a point lies within a polygon using PHP?

PHP Implementation for Locating Points Within a Polygon

Question:

Given an array of latitude and longitude coordinates representing a polygon and a point with similar coordinates, how can we determine if the point lies within the polygon?

Solution:

<br>$vertices_x = array(37.628134, 37.629867, 37.62324, 37.622424);    // x-coordinates of polygon vertices<br>$vertices_y = array(-77.458334,-77.449021,-77.445416,-77.457819); // y-coordinates of polygon vertices<br>$points_polygon = count($vertices_x) - 1;  // number of polygon vertices<br>$longitude_x = $_GET["longitude"];  // x-coordinate of test point<br>$latitude_y = $_GET["latitude"];    // y-coordinate of test point</p>
<p>if (is_in_polygon($points_polygon, $vertices_x, $vertices_y, $longitude_x, $latitude_y)){<br>  echo "Point is within polygon!";<br>}<br>else echo "Point is not within polygon";</p>
<p>function is_in_polygon($points_polygon, $vertices_x, $vertices_y, $longitude_x, $latitude_y)<br>{<br>  $i = $j = $c = 0;<br>  for ($i = 0, $j = $points_polygon ; $i < $points_polygon; $j = $i  ) {</p><pre class="brush:php;toolbar:false">if ( (($vertices_y[$i]  >  $latitude_y != ($vertices_y[$j] > $latitude_y)) &amp;&amp;
 ($longitude_x < ($vertices_x[$j] - $vertices_x[$i]) * ($latitude_y - $vertices_y[$i]) / ($vertices_y[$j] - $vertices_y[$i]) + $vertices_x[$i]) ) )
   $c = !$c;

}
return $c;
}

In this PHP code, the is_in_polygon function iterates through each edge of the polygon, checking if the point is on the "side" of the polygon where the y-coordinate of one vertex is greater than the test point's y-coordinate and the other vertex's y-coordinate is less than the test point's y-coordinate. If both of these conditions are true, the function checks if the x-coordinate of the test point is less than the line segment between the two vertices. If so, it signifies a crossing of the polygon boundary and adds or subtracts 1 from a counter. Finally, if that counter is nonzero, it indicates that the test point is within the polygon.

Additional Resources:

For further support, consider using the polygon.php class, which provides an additional function, isInside, for determining if a point is within a polygon.

The above is the detailed content of How can we determine if a point lies within a polygon using PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn