Web/PHP

PHP] map 폴리곤(Polygon) 영역의 중심 좌표 구하기

projin 2021. 11. 5. 10:09

 

폴리곤 영역안의 중심 좌표를 구하는 함수입니다.

//중심 좌표 구하기
/*******************************/

function get_center($coords)
{
    $count_coords = count($coords);
    $xcos=0.0;
    $ycos=0.0;
    $zsin=0.0;

    foreach ($coords as $lnglat)
    {
        $lat = $lnglat['lat'] * pi() / 180;
        $lon = $lnglat['lng'] * pi() / 180;

        $acos = cos($lat) * cos($lon);
        $bcos = cos($lat) * sin($lon);
        $csin = sin($lat);
        $xcos += $acos;
        $ycos += $bcos;
        $zsin += $csin;
    }

    $xcos /= $count_coords;
    $ycos /= $count_coords;
    $zsin /= $count_coords;
    $lon = atan2($ycos, $xcos);
    $sqrt = sqrt($xcos * $xcos + $ycos * $ycos);
    $lat = atan2($zsin, $sqrt);

    return array($lat * 180 / pi(), $lon * 180 / pi());
}


$coords[]=array('lat' => '35.2442492','lng'=>'129.0903149');
$coords[]=array('lat' => '35.2440576','lng'=>'129.0905777');
$coords[]=array('lat' => '35.2438385','lng'=>'129.0902934');
$coords[]=array('lat' => '35.2440751','lng'=>'129.0900976');

$center_map = get_center($coords);

$center_lat = $center_map[0];
$center_lng = $center_map[1];