在纬度和经度的多边形内找到一个点

时间:2014-07-16 04:48:30

标签: php google-maps polygon point-in-polygon

以下是我修改并从此问题中获取的代码Find Point in polygon PHP

顶点x和y形成一个矩形..即使点y和x在多边形内部,我仍然无法使其工作,但它没有显示正确的结果。我做错了什么这里..

<?php
$vertices_x = array(45.007243,45.007243,46.3734,46.3734); // x-coordinates of the vertices of the polygon
$vertices_y = array(-75.007095,-72.506332,-72.506332,-75.007095,); // y-coordinates of the vertices of the polygon
$points_polygon = count($vertices_x); 
$latitude_y =  45.5086699;  // x-coordinate of the point to test
$longitude_x = -73.553992; 

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-1 ; $i < $points_polygon; $j = $i++) {
    if ( (($vertices_y[$i] > $latitude_y != ($vertices_y[$j] > $latitude_y)) &&
    ($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;
}
?>

1 个答案:

答案 0 :(得分:0)

一个问题是latitude_y和longitude_x变量的初始化:

latitude_y appears to contain the 'x' coordinate.
longitude_x appears to contain the 'y' coordinate.