Web/PHP

현 위치에서 좌표 내부에 있는지 판단하는 알고리즘

projin 2021. 10. 28. 10:42
class Point {
    public $lat;
    public $long;
    function Point($lat, $long) {
        $this->lat = $lat;
        $this->long = $long;
    }
}


//the Point in Polygon function
function pointInPolygon($p, $polygon) {
    //if you operates with (hundred)thousands of points
    set_time_limit(60);
    $c = 0;
    $p1 = $polygon[0];
    $n = count($polygon);

    for ($i=1; $i<=$n; $i++) {
        $p2 = $polygon[$i % $n];
        if ($p->long > min($p1->long, $p2->long)
            && $p->long <= max($p1->long, $p2->long)
            && $p->lat <= max($p1->lat, $p2->lat)
            && $p1->long != $p2->long) {
            $xinters = ($p->long - $p1->long) * ($p2->lat - $p1->lat) / ($p2->long - $p1->long) + $p1->lat;
            if ($p1->lat == $p2->lat || $p->lat <= $xinters) {
                $c++;
            }
        }
        $p1 = $p2;
    }
    // if the number of edges we passed through is even, then it's not in the poly.
    return $c%2!=0;
}


$arr = array();
unset($list);
$sql_query = "select * from map_line_t";
$list = $DB->select_query($sql_query);

if($list) {
    foreach($list as $row) {
        $arr[] = new Point($row['rl_map_lat'], $row['rl_map_lng']);
    }
}
$polygon = $arr;

/*
$polygon = array(
    new Point(35.2440904,129.090543),
    new Point(35.2438473,129.0902734),
    new Point(35.2438046,129.0903405),
    new Point(35.2440379,129.0906006),
);
*/

function ParkLine($lat, $lng) {
    global $polygon;
    $latlng=$lat.','.$lng;
    echo (pointInPolygon(new Point($lat,$long), $polygon)) ? $latlng .' is inside polygon<br>' : $latlng.' is outside<br>';
    
}


ParkLine(35.2439421, 129.0904429);
ParkLine(35.2441031, 129.0904939);

 

카카오맵 폴리곤 지도 내부에 좌표가 있는지 확인

 

https://webinstory.tistory.com/entry/%EC%B9%B4%EC%B9%B4%EC%98%A4%EB%A7%B5-%ED%8F%B4%EB%A6%AC%EA%B3%A4-%EC%A7%80%EB%8F%84-%EB%82%B4%EB%B6%80%EC%97%90-%EC%A2%8C%ED%91%9C%EA%B0%80-%EC%9E%88%EB%8A%94%EC%A7%80-%ED%99%95%EC%9D%B8

 

 

https://pythonq.com/so/php/490130

https://stackoverflow.com/questions/14818567/point-in-polygon-algorithm-giving-wrong-results-sometimes