If I have coordinates of center point of circle, circle radius and also coordinates of the point that need to be check if a point lies inside or on the boundary of the Circle.
- $circle_x and $circle_y => center point latitude and longitude of the circle
- $rad => radius(Meter) of the circle
- $x and $y => latitude and longitude of the point that need to be check
I have tried 2 ways,
public function pointInCircle($circle_x, $circle_y, $rad, $x, $y)
{
$dx = abs($x - $circle_x);
$dy = abs($y - $circle_y);
$R = $rad;
if ($dx + $dy <= $R) {
return "inside";
} else if ($dx > $R) {
return "outside";
} else if ($dy > $R) {
return "outside";
} else if ($dx ^ 2 + $dy ^ 2 <= $R ^ 2) {
return "inside";
} else {
return "outside";
}
}
Second method is,
public function pointInCircle($circle_x, $circle_y, $rad, $x, $y)
{
if ((($x - $circle_x) * ($x - $circle_x) + ($y - $circle_y) * ($y - $circle_y)) <= ($rad * $rad)){
return "inside";
} else {
return "outside";
}
}
But above 2 methods couldn’t provide correct result, please help to find if provided point lies inside or on the boundary of the Circle using PHP.
2
Answers
To solve this problem on the earth surface with latidute/longitude coordinates, you need to apply spherical geometry.
Look here at Distance section and modify code for PHP.
P.S. Found PHP implementation here at SO.
If result distance is less than your
$rad
, point with given coordinates lies inside the circlenow
Note – I supposed that latitude corresponds to Y-coordinate, and longitude – to X-coordinates, as maps usually are drawn. Swap x/y if I’m not right
(Test here) gives OUTSIDE for small $rad and Inside for large radius
Broke down the code (partially the code you provided) into separate line to easily debug as needed.