Skip to main content

Fencing ( Latitude Longitude )

 Check Lat/Long is Inside/Outside of fencing


<?php

function onLine($side,$point)  //check whether p is on the line or not

{


  if($point['x'] <= max($side['x']['x'], $side['y']['x']) && $point['x'] <= min($side['x']['x'], $side['y']['x']) &&

   ($point['y'] <= max($side['x']['y'], $side['y']['y']) && $point['y'] <= min($side['x']['y'], $side['y']['y'])))

      return true;


return false;

}

function direction($point1,$point2,$point3)

{

   $val=($point2['y']-$point1['y'])*($point3['x']-$point2['x'])-($point2['x']-$point1['x'])*($point3['y']-$point2['y']);

   if ($val == 0)

   return 0; //colinear

   else if($val <0)

   return 2;          //anti-clockwise direction

   return 1;          //clockwise direction


}

function isIntersect($side,$exline)

{


  //four direction for two lines and points of other line

 $dir1 = direction($side['x'], $side['y'], $exline['x']);

 $dir2 = direction($side['x'], $side['y'], $exline['y']);

 $dir3 = direction($exline['x'], $exline['y'], $side['x']);

 $dir4 = direction($exline['x'], $exline['y'], $side['y']);


 if($dir1 != $dir2 && $dir3 != $dir4)

   return true;           //they are intersecting

if($dir1==0 && onLine($side, $exline['x']))        //when p2 of line2 are on the line1

   return true;

if($dir2==0 && onLine($side, $exline['y']))         //when p1 of line2 are on the line1

   return true;

if($dir3==0 && onLine($exline, $side['x']))       //when p2 of line1 are on the line2

   return true;

if($dir4==0 && onLine($exline, $side['y'])) //when p1 of line1 are on the line2

   return true;

return false;


}

function checkInside($polygon,$point,$n)

{

  if($n < 3) //when polygon has less than 3 edge, it is not polygon

   return false;

echo "<pre>";

   $exline=array('x'=>$point,'y'=>array('x'=>999999,'y'=>$point['y']));//create a point at infinity, y is same as point p

   $count=0;

   $i=0;

   do {

     $m=($i+1)%$n;

     $side=array('x'=>$polygon[$i],'y'=>$polygon[$m]);//forming a line from two consecutive points of poly


     if(isIntersect($side,$exline))  //if side is intersects exline

     {

       if(direction($side['x'], $point, $side['y']) == 0)

            return onLine($side, $point);

             $count++;

     }


     $i = ($i+1)%$n;

   }

   while($i != 0);

   return $count&1;


}

$polygon=array(

          array('x'=>0,'y'=>0),

          array('x'=>10,'y'=>0),

          array('x'=>10,'y'=>10),

          array('x'=>0,'y'=>10));

$point=array('x'=>9,

            'y'=>9);

$n=4;

if(checkInside($polygon,$point,$n))

{

echo "User is inside the Polygon";


}

else {

  echo "User is outside the Polygon";

}

?>


Comments