在PHP中检测多边形内的地理坐标

时间:2014-07-23 13:48:26

标签: php

我有以下一组坐标:

24.086589258228027, 51.6796875:
22.87744046489713,  52.6025390625:
22.715390019335942, 55.1953125:
21.90227796666864,  55.72265625:
19.89072302399691,  54.9755859375:
18.396230138028827, 48.4716796875:
21.657428197370653, 46.58203125

现在,如果我有一个坐标集(单纬度长集),我怎么能检测到这个位置是否位于该多边形区域内?

1 个答案:

答案 0 :(得分:8)

这对我有用

$polyX    =  array();//horizontal coordinates of corners
$polyY    =  array();//vertical coordinates of corners

$zonal  =   "14.519780046326085,82.7490234375:8.276727101164045,88.9453125:3.7327083213358465,77.958984375:5.134714634014455,77.1240234375:7.493196470122287,76.552734375:10.18518740926906,75.498046875:11.781325296112277,75.05859375:13.539200668930814,80.2001953125:14.519780046326085,82.7490234375"; 

$zonalArray =   explode(":",$zonal);
$polySides  = count($zonalArray); //how many corners the polygon has 
foreach($zonalArray as $eachZoneLatLongs)
{
    $latlongArray   =   explode(",",$eachZoneLatLongs);
    $polyX[]    =   $latlongArray[0];
    $polyY[]    =   $latlongArray[1];
}




$vertices_x = $polyX;    // x-coordinates of the vertices of the polygon
$vertices_y = $polyY; // y-coordinates of the vertices of the polygon
#$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); // number vertices
#Following Points lie inside this region
$longitude_x = 6.927079 ;  // x-coordinate of the point to test
$latitude_y = 79.861243;    // y-coordinate of the point to test 

#Following Points lie outside this region
#$longitude_x = 27.175015 ;  // x-coordinate of the point to test
#$latitude_y = 78.042155;    // 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-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;
}