Geo Fencing - point inside/outside polygon

后端 未结 16 1763
我在风中等你
我在风中等你 2020-11-28 02:15

I would like to determine a polygon and implement an algorithm which would check if a point is inside or outside the polygon.

Does anyone know if there is any exampl

16条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-28 02:53

    I translated c# method in Php and I added many comments to understand code.

    Description of PolygonHelps:
    Check if a point is inside or outside of a polygon. This procedure uses gps coordinates and it works when polygon has a little geographic area.


    INPUT:
    $poly: array of Point: polygon vertices list; [{Point}, {Point}, ...];
    $point: point to check; Point: {"lat" => "x.xxx", "lng" => "y.yyy"}


    When $c is false, the number of intersections with polygon is even, so the point is outside of polygon;
    When $c is true, the number of intersections with polygon is odd, so the point is inside of polygon;
    $n is the number of vertices in polygon;
    For each vertex in polygon, method calculates line through current vertex and previous vertex and check if the two lines have an intersection point.
    $c changes when intersection point exists.
    So, method can return true if point is inside the polygon, else return false.

    class PolygonHelps {
    
        public static function isPointInPolygon(&$poly, $point){
    
            $c = false; 
            $n = $j = count($poly);
    
    
            for ($i = 0, $j = $n - 1; $i < $n; $j = $i++){
    
                if ( ( ( ( $poly[$i]->lat <= $point->lat ) && ( $point->lat < $poly[$j]->lat ) ) 
                    || ( ( $poly[$j]->lat <= $point->lat ) && ( $point->lat < $poly[$i]->lat ) ) ) 
    
                && ( $point->lng <   ( $poly[$j]->lng - $poly[$i]->lng ) 
                                   * ( $point->lat    - $poly[$i]->lat ) 
                                   / ( $poly[$j]->lat - $poly[$i]->lat ) 
                                   +   $poly[$i]->lng ) ){
    
                    $c = !$c;
                }
            }
    
            return $c;
        }
    }
    

提交回复
热议问题