原文地址 https://xiegaosheng.com/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 表示点的上下左右的区域