## 如何使用 PHP 決定一個點是否位於多邊形內?

Susan Sarandon
發布: 2024-10-25 03:53:02
原創
353 人瀏覽過

## 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中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!