Home > Database > Mysql Tutorial > body text

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

Barbara Streisand
Release: 2024-10-31 03:58:30
Original
129 people have browsed it

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!