我想用PHP编写一些代码,根据多边形的坐标检查单个经度/经度坐标。 并返回 true 或 false,无论它存在于多边形内。
例如,我在这里创建了一个多边形。http://www.geocodezip.com/polygonTool.asp
0: 53.34545,-6.2550831: 53.340121,-6.2390332: 53.338788,-6.2389473: 53.337405,-6.2404924: 53.334227,-6.2456425: 53.332074,-6.2529376: 53.330024,-6.2643537: 53.333766,-6.2648688: 53.33761,-6.2658129: 53.338583,-6.26615510: 53.341607,-6.26538311: 53.342683,-6.26443912: 53.344067,-6.26469613: 53.344733,-6.259632
我有一个用户位置作为...53.338839, -6.249386 (确实存在于此多边形内(。
有没有一种简单的方法来验证这是在多边形内部还是外部?
查找点是否在多边形中的一种方法是计算从该点(在任何方向上(绘制的线与多边形边界相交的次数。如果它们相交偶数次,那么点就在外面。
以下 PHP 代码需要 2 个数组$polyX = 多边形经度点的数组。重复第一个点以闭合多边形。$polyy = 多边形的纬度点数组,
$polySides = 13; //how many corners the polygon has
$polyX = array(53.34545,53.340121,53.338788,53.337405,53.334227,53.332074,53.330024,53.333766,53.33761,53.338583,53.341607,53.342683,53.344067,53.344733,53.34545);
$polyY = array(6.255083,-6.239033,-6.238947,-6.240492,-6.245642,-6.252937,-6.264353,-6.264868,-6.265812,-6.266155,-6.265383,-6.264439,-6.264696,-6.259632,6.255083);
$x =53.338839;//your coordinates
$y =-6.249386;
function pointInPolygon($polySides,$polyX,$polyY,$x,$y) {
$j = $polySides-1 ;
$oddNodes = 0;
for ($i=0; $i<$polySides; $i++) {
if ($polyY[$i]<$y && $polyY[$j]>=$y
|| $polyY[$j]<$y && $polyY[$i]>=$y) {
if ($polyX[$i]+($y-$polyY[$i])/($polyY[$j]-$polyY[$i])*($polyX[$j]-$polyX[$i])<$x) {
$oddNodes=!$oddNodes; }}
$j=$i; }
return $oddNodes; }
if (pointInPolygon($polySides,$polyX,$polyY,$x,$y)){
echo "Is in polygon!";
}
else echo "Is not in polygon";
请参阅此内容以了解 JavaScript 实现。
从我的大地测量类来看,基本功能是:
function isInRegion(Geodetic_LatLong $position)
{
$latitude = $position->getLatitude()->getValue();
$longitude = $position->getLongitude()->getValue();
$perimeterNodeCount = count($this->_nodePoints);
$jIndex = $perimeterNodeCount - 1 ;
$oddNodes = FALSE;
for ($iIndex = 0; $iIndex < $perimeterNodeCount; ++$iIndex) {
$iLatitude = $this->_nodePoints[$iIndex]->getLatitude()->getValue();
$jLatitude = $this->_nodePoints[$jIndex]->getLatitude()->getValue();
if (($iLatitude < $latitude && $jLatitude >= $latitude) ||
($jLatitude < $latitude && $iLatitude >= $latitude)) {
$iLongitude = $this->_nodePoints[$iIndex]->getLongitude()->getValue();
$jLongitude = $this->_nodePoints[$jIndex]->getLongitude()->getValue();
if ($iLongitude +
($latitude - $iLatitude) /
($jLatitude - $iLatitude) * ($jLongitude - $iLongitude) < $longitude) {
$oddNodes = !$oddNodes;
}
}
$jIndex = $iIndex;
}
return $oddNodes;
}