Finding Points Within a Polygon Using PHP
Problem:
Given a polygon defined by an array of latitude and longitude coordinates and a point (vertex) with known coordinates, determine whether the vertex lies within the polygon.
Solution:
To solve this problem, we utilize an adapted version of a polygon intersection algorithm:
<code class="php">function is_in_polygon($points_polygon, $vertices_x, $vertices_y, $longitude_x, $latitude_y) { $i = $j = $c = 0; for ($i = 0, $j = $points_polygon ; $i < $points_polygon; $j = $i++) { if ( (($vertices_y[$i] > $latitude_y != ($vertices_y[$j] > $latitude_y)) && ($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; }</code>
This function iterates through the vertices of the polygon, calculating the intersection of lines formed by the vertex and subsequent vertices with a horizontal line passing through the point to be tested. If the intersection point lies to the left of the vertex for all lines, the point is outside the polygon; otherwise, it is inside.
Example:
<code class="php">$vertices_x = array(37.628134, 37.629867, 37.62324, 37.622424); $vertices_y = array(-77.458334,-77.449021,-77.445416,-77.457819); $points_polygon = count($vertices_x) - 1; $longitude_x = $_GET["longitude"]; $latitude_y = $_GET["latitude"]; if (is_in_polygon($points_polygon, $vertices_x, $vertices_y, $longitude_x, $latitude_y)){ echo "Is in polygon!"; } else echo "Is not in polygon";</code>
Additional Notes:
For more complex operations involving polygons, consider using the polygon.php class available online.
The above is the detailed content of How to Determine if a Point Lies Within a Polygon Using PHP?. For more information, please follow other related articles on the PHP Chinese website!