Home  >  Article  >  Database  >  How to Determine if a Point Lies Within a Polygon Using PHP?

How to Determine if a Point Lies Within a Polygon Using PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-10-26 01:45:02547browse

How to Determine if a Point Lies Within a Polygon Using PHP?

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)) &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;
}</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!

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