首页  >  文章  >  数据库  >  ## 如何使用 PHP 确定一个点是否位于多边形内?

## 如何使用 PHP 确定一个点是否位于多边形内?

Susan Sarandon
Susan Sarandon原创
2024-10-25 03:53:02354浏览

## How do you determine if a point lies within a polygon using PHP?

确定一个点是否位于多边形内

在空间分析领域,人们经常遇到确定给定点是否位于多边形内的问题位于多边形的边界内。当处理由多个顶点定义的复杂几何形状时,这尤其具有挑战性。 MySQL 的几何数据类型包含一个多边形类型来表示此类形状。

考虑这样的场景,我们有一组表示多边形顶点的纬度和经度,如下所示:

[{"x":37.628134,  "y":-77.458334},
{"x":37.629867,   "y":-77.449021},
{"x":37.62324,    "y":-77.445416},
{"x":37.622424,   "y":-77.457819}]

另外,我们有一个点有自己的纬度和经度坐标:

$location = new vertex($_GET["longitude"], $_GET["latitude"]);

任务是确定这个点是否落在指定的多边形内。要在 PHP 中完成此操作,我们可以使用以下函数:

<?php
$vertices_x = array(37.628134, 37.629867, 37.62324, 37.622424);    // x-coordinates of the vertices of the polygon
$vertices_y = array(-77.458334,-77.449021,-77.445416,-77.457819); // y-coordinates of the vertices of the polygon
$points_polygon = count($vertices_x) - 1;  // number vertices - zero-based array
$longitude_x = $_GET["longitude"];  // x-coordinate of the point to test
$latitude_y = $_GET["latitude"];    // y-coordinate of the point to test

if (is_in_polygon($points_polygon, $vertices_x, $vertices_y, $longitude_x, $latitude_y)){
  echo "Is in polygon!";
}
else echo "Is not in polygon";

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;
}
?>

此函数迭代多边形的顶点,并利用几何计算来确定该点是否位于其边界内。根据结果​​,它返回一个标志,指示该点是在多边形内部还是外部。

要获得更全面的功能,请考虑使用 Polygon.php 类。通过使用多边形的顶点创建此类的实例并以点作为输入调用 isInside() 方法,您可以利用替代方法来解决此问题。

以上是## 如何使用 PHP 确定一个点是否位于多边形内?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn