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.
CodePudding user response:
Broke down the code (partially the code you provided) into separate line to easily debug as needed.
function pointInCircle($circle_x, $circle_y, $rad, $x, $y)
{
$dx = ($x - $circle_x);
$dy = ($y - $circle_y);
$dx = $dx * $dx;
$dy = $dy * $dy;
$dist = $dx $dy; //eqt of distance.
$str = "outside";
if ( $dist <= $rad * $rad)
$str = "inside";
return $str;
}
echo " result " . pointInCircle(0,0,25,4,4);
CodePudding user response:
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 circle
function haversineGreatCircleDistance(
$latitudeFrom, $longitudeFrom, $latitudeTo, $longitudeTo, $earthRadius = 6371000)
{
// convert from degrees to radians
$latFrom = deg2rad($latitudeFrom);
$lonFrom = deg2rad($longitudeFrom);
$latTo = deg2rad($latitudeTo);
$lonTo = deg2rad($longitudeTo);
$latDelta = $latTo - $latFrom;
$lonDelta = $lonTo - $lonFrom;
$angle = 2 * asin(sqrt(pow(sin($latDelta / 2), 2)
cos($latFrom) * cos($latTo) * pow(sin($lonDelta / 2), 2)));
return $angle * $earthRadius;
}
now
if (haversineGreatCircleDistance($circle_y, $circle_x, $y, $x) < $rad)
point i circle
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