小謝博客https://xgs888.top/post/view?id=77
PHP判斷一個點在矩形區域什麼位置;隨便標記一個點就生成點的上下最有區域的id;
首先需要準備區域表fgareadata 和點區域對應表 point_region;
/**
* Created by PhpStorm.
* function: getRegion
* User: xiaoxie
* Description:計算點所在區域
* @param $x
* @param $y
* @param $floor_id
* @param $id
* @param string $location
*
*/
public function getRegion($x,$y,$floor_id,$id,$location='')
{
$maxxc = 2;//點到區域的最大間隔x
$maxxy = 2;//點到區域的最大間隔y
$where['floor_id'] =$floor_id;
if ($location)
{
//如果是修改的話需要先清除方向
$dataarr['tops'] = null;
$dataarr['downs'] = null;
$dataarr['lefts'] = null;
$dataarr['rights'] = null;
$dataarr['times'] =time();
DB::table('point_region')->where('id='.$id)->update($dataarr);
}
$lists = Db::table('fgareadata')->where($where)->select();
if ($lists)
{
foreach ($lists as $list)
{
$xarr = [];
$yarr = [];
$datas = [];
$data = explode('|',$list['data']);
foreach ($data as $key=>$value)
{
$dataarr = explode(',',$value);
//將x,y座標存到數組裏
$xarr[] = $dataarr[0];
$yarr[] = $dataarr[1];
}
//取出數組中的最大x,y值
$minx = min($xarr);
$maxx = max($xarr);
$miny = min($yarr);
$maxy = max($yarr);
//判斷左右
if($y>$miny && $y<$maxy)
{
//先判斷y座標是否在區域內,然後去判斷區域是在做還是右
if ($x >$maxx & $x- $maxx < $maxxc)
{
$datas['lefts'] = $list['Id'];
}
//如果x小於最小的x座標 取到點的右側區域
if($x < $minx && $minx-$x <$maxxc)
{
$datas['rights'] = $list['Id'];
}
}
//判斷上下
if ($x>$minx && $x<$maxx)
{
if($y>$maxy && $y-$maxy < $maxxy)
{
$datas['downs'] = $list['Id'];
}
if ($y< $miny && $miny - $y < $maxxy)
{
$datas['tops'] = $list['Id'];
}
}
if($datas)
{
//樓層id
$datas['floor_id'] = $floor_id;
$datas['times'] = time();
DB::table('point_region')->where('id='.$id)->update($datas);
}
}
}
}
效果圖如下
數據庫生成數據
tops,lefts,downs,rights 表示點的上下左右的區域