Web/PHP

PHP] 네이버맵 API를 이용한 좌표로 주소구하기

projin 2021. 11. 5. 10:13

네이버맵 API를 이용한 좌표로 주소를 구할 수 있으며 반대로 주소로 해당 좌표도 구할 수 있습니다.

네이버맵 API 가이드
https://api.ncloud-docs.com/docs/ai-naver-mapsreversegeocoding-gc

<?php

function getNaverGeocode($addr, $center_lat, $center_lng) {
    $addr = urlencode($addr);
    //주소로 좌표
    $url = "https://naveropenapi.apigw.ntruss.com/map-geocode/v2/geocode?query=".$addr;

    //좌표를 주소 변환
    $url ="https://naveropenapi.apigw.ntruss.com/map-reversegeocode/v2/gc?request=coordsToaddr&coords=".$center_lng.",".$center_lat."&sourcecrs=epsg:4326&output=json&orders=addr,admcode,roadaddr";
    //$url ="https://naveropenapi.apigw.ntruss.com/map-reversegeocode/v2/gc?request=coordsToaddr&coords=129.09166842734442,35.24305042095739&sourcecrs=epsg:4326&output=json&orders=addr,admcode,roadaddr";
    $headers = array();
    $headers[] ="X-NCP-APIGW-API-KEY-ID:4qmz0qmy89";
    $headers[] ="X-NCP-APIGW-API-KEY:qsNi179YHQZWYpGZxkKqj2ZDleMSHDzvFG2RoAdj";

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    curl_close($ch);

    return $result;
}


$addr = "서울특별시 중구 예장동 산5-6";
$center_lat = "37.551968838145136";
$center_lng = "126.98804354028125";


//주소로 좌표 구하기
//$geo_latlng = getNaverGeocode($addr, $center_lat = "", $center_lng = "");
//$data = json_decode($geo_latlng,1);

//좌표로 주소구하기
$geo_address = getNaverGeocode($addr = "", $center_lat, $center_lng);
$data = json_decode($geo_address,1);

//지번 주소
if($data['results'][0][name]=="addr") {
    $sido = $data['results'][0][region][area1][name];
    $gugun = $data['results'][0][region][area2][name];
    $dong = $data['results'][0][region][area3][name];
    $li = $data['results'][0][region][area4][name];

    $landType = $data['results'][0][land][type];
    if ($landType == "2") $landTypeTxt = "산";
    $jibun1 = $data['results'][0][land][number1];
    $jibun2 = $data['results'][0][land][number2];

    if ($jibun1) {
    $jibun = ($jibun2) ? $landTypeTxt . $jibun1 . "-" . $jibun2 : $landTypeTxt . $jibun1;
    }

    $rp_address = $sido . " " . $gugun . " " . $dong . " " . $li . " " . $jibun;
    //echo $rp_address;
}

//도로명 주소
if($data['results'][2][name]=="roadaddr"){
    $sido = $data['results'][2][region][area1][name];
    $gugun = $data['results'][2][region][area2][name];
    $dong = $data['results'][2][region][area3][name];

    $road_name = $data['results'][2][land][name];
    $road1 = $data['results'][2][land][number1];
    $road2 = $data['results'][2][land][number2];
    $building = $data['results'][2][land][addition0][value];

    if ($road1) {
    $road = ($road2) ? $road1 . "-" . $road2 : $road1;
    }

    $rp_address_road = $sido . " " . $gugun . " " . $road_name . " " . $road ." ". $building;
    //echo $rp_address_road;
}


좌표로 주소를 구한 결과 : 서울특별시 중구 예장동 산5-6
?>