ホームページ  >  記事  >  データベース  >  ## 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 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。