Home  >  Article  >  Database  >  How can I determine if a point is inside a polygon in PHP?

How can I determine if a point is inside a polygon in PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-10-31 03:58:30117browse

How can I determine if a point is inside a polygon in PHP?

Point-in-Polygon Algorithm in PHP

Problem:

Given an array of latitude and longitude coordinates defining a polygon and a point with similar coordinates, determine if the point lies within the polygon's boundaries.

Implementation:

PHP provides a function for solving this problem, using a classic point-in-polygon algorithm. The function is:

<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>

Usage:

To use the function, provide it with the following parameters:

  • $points_polygon: The number of vertices in the polygon (zero-based array).
  • $vertices_x: An array of x-coordinates for the polygon's vertices.
  • $vertices_y: An array of y-coordinates for the polygon's vertices.
  • $longitude_x: The x-coordinate of the point to test.
  • $latitude_y: The y-coordinate of the point to test.

The function returns true if the point lies within the polygon and false otherwise.

Additional Note:

PHP also provides a polygon.php class that contains several polygon-related functions, including isInside, which can be used to determine if a point is within a polygon.

The above is the detailed content of How can I determine if a point is inside a polygon in 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