JAVASCRIPT

브이월드 2D데이터 api react nextjs 사용법

Neda 2023. 5. 4. 23:09

1. 브이월드 API 사용법

1. 1 브이월드 가입

api 호출에 필요한 인증키를 받기 위해 회원가입은 필수입니다.

 

공간정보 오픈플랫폼

국가가 보유하고 있는 공개 가능한 공간정보를 모든 국민이 자유롭게 활용할 수 있도록 다양한 방법을 제공합니다.

www.vworld.kr

 

1.2 파라미터 세팅

api 호출에 필요한 파라미터를 객체 형태로 세팅.

아래 파라미터는 예제에 있는 파라미터로

한반도 전체 지역을 범위로 하여(geomfilter)

국내의 광역시도 정보(data)를 가져오는 파라미터

const params = {
    key: "인증키",
    domain: "http://localhost:3000/",
    service: "data",
    version: "2.0",
    request: "getfeature",
    format: "json",
    size: "1000",
    page: "1",
    geometry: "false",
    attribute: "true",
    crs: "EPSG:4326",
    geomfilter:
      "BOX(122.77143441739624,  32.689674111652815,  133.16466627619113,  42.0516845871052)",
    data: "LT_C_ADSIDO_INFO",
  };

 

1.3 api를 호출하는 fetch 함수

url과 params를 합쳐 fetch()함수를 호출

export const fetchRegionData = async (url, params) => {
  const URLparams = new URLSearchParams(params);
  try {
    const res = await fetch(url + URLparams);
    const json = await res.json();
    console.log("fetch success");
    return json;
  } catch (error) {
    console.log("fetch error: ", error);
  }
};

 

1.4 api 호출하고 응답받기

요청 URL은 'http://api.vworld.kr/req/data' 아래에서 rewrites를 통해

목적지를 http://api.vworld.kr 로 지정하기 때문에 도메인은 생략한다.

const getSido = async () => {
	cosnt data = await fetchRegionData('req/data?',params);
    return data
}

1.4 nextjs 환경에서 cors 문제 해결

html에서 <script>를 사용하면 jsonp를 사용할 수 있다.

nextjs에서는 rewrites()를 사용해 url 프록시 역할을 수행하여 cors 문제를 피한다.

 

next.config.js: Rewrites | Next.js

Add rewrites to your Next.js app.

nextjs.org

/* config 파일 경로: /next.config.js */
const nextConfig = {
  ...,
  async rewrites() {
    return [
      {
        source: "/:path*",
        destination: "https://api.vworld.kr/:path*",
      },
    ];
  },
};

module.exports = nextConfig;

 

 

1.5. fetch 결과 

2D 데이터 api 2.0 광역시도 검색 결과

{
  "response": {
    "service": {
      "name": "data",
      "version": "2.0",
      "operation": "getfeature",
      "time": "472(ms)"
    },
    "status": "OK",
    "record": {
      "total": "17",
      "current": "17"
    },
    "page": {
      "total": "1",
      "current": "1",
      "size": "1000"
    },
    "result": {
      "featureCollection": {
        "type": "FeatureCollection",
        "bbox": [
          0,
          0,
          -1,
          -1
        ],
        "features": [
          {
            "type": "Feature",
            "properties": {
              "ctp_eng_nm": "Seoul",
              "ctprvn_cd": "11",
              "ctp_kor_nm": "서울특별시"
            },
            "id": "LT_C_ADSIDO_INFO.392"
          },
          {
            "type": "Feature",
            "properties": {
              "ctp_eng_nm": "Busan",
              "ctprvn_cd": "26",
              "ctp_kor_nm": "부산광역시"
            },
            "id": "LT_C_ADSIDO_INFO.393"
          },
          {
            "type": "Feature",
            "properties": {
              "ctp_eng_nm": "Daegu",
              "ctprvn_cd": "27",
              "ctp_kor_nm": "대구광역시"
            },
            "id": "LT_C_ADSIDO_INFO.394"
          },
          {
            "type": "Feature",
            "properties": {
              "ctp_eng_nm": "Incheon",
              "ctprvn_cd": "28",
              "ctp_kor_nm": "인천광역시"
            },
            "id": "LT_C_ADSIDO_INFO.395"
          },
          {
            "type": "Feature",
            "properties": {
              "ctp_eng_nm": "Gwangju",
              "ctprvn_cd": "29",
              "ctp_kor_nm": "광주광역시"
            },
            "id": "LT_C_ADSIDO_INFO.396"
          },
          {
            "type": "Feature",
            "properties": {
              "ctp_eng_nm": "Daejeon",
              "ctprvn_cd": "30",
              "ctp_kor_nm": "대전광역시"
            },
            "id": "LT_C_ADSIDO_INFO.397"
          },
          {
            "type": "Feature",
            "properties": {
              "ctp_eng_nm": "Ulsan",
              "ctprvn_cd": "31",
              "ctp_kor_nm": "울산광역시"
            },
            "id": "LT_C_ADSIDO_INFO.398"
          },
          {
            "type": "Feature",
            "properties": {
              "ctp_eng_nm": "Sejong-si",
              "ctprvn_cd": "36",
              "ctp_kor_nm": "세종특별자치시"
            },
            "id": "LT_C_ADSIDO_INFO.399"
          },
          {
            "type": "Feature",
            "properties": {
              "ctp_eng_nm": "Gyeonggi-do",
              "ctprvn_cd": "41",
              "ctp_kor_nm": "경기도"
            },
            "id": "LT_C_ADSIDO_INFO.400"
          },
          {
            "type": "Feature",
            "properties": {
              "ctp_eng_nm": "Gangwon-do",
              "ctprvn_cd": "42",
              "ctp_kor_nm": "강원도"
            },
            "id": "LT_C_ADSIDO_INFO.401"
          },
          {
            "type": "Feature",
            "properties": {
              "ctp_eng_nm": "Chungcheongbuk-do",
              "ctprvn_cd": "43",
              "ctp_kor_nm": "충청북도"
            },
            "id": "LT_C_ADSIDO_INFO.402"
          },
          {
            "type": "Feature",
            "properties": {
              "ctp_eng_nm": "Chungcheongnam-do",
              "ctprvn_cd": "44",
              "ctp_kor_nm": "충청남도"
            },
            "id": "LT_C_ADSIDO_INFO.403"
          },
          {
            "type": "Feature",
            "properties": {
              "ctp_eng_nm": "Jeollabuk-do",
              "ctprvn_cd": "45",
              "ctp_kor_nm": "전라북도"
            },
            "id": "LT_C_ADSIDO_INFO.404"
          },
          {
            "type": "Feature",
            "properties": {
              "ctp_eng_nm": "Jellanam-do",
              "ctprvn_cd": "46",
              "ctp_kor_nm": "전라남도"
            },
            "id": "LT_C_ADSIDO_INFO.405"
          },
          {
            "type": "Feature",
            "properties": {
              "ctp_eng_nm": "Gyeongsangbuk-do",
              "ctprvn_cd": "47",
              "ctp_kor_nm": "경상북도"
            },
            "id": "LT_C_ADSIDO_INFO.406"
          },
          {
            "type": "Feature",
            "properties": {
              "ctp_eng_nm": "Gyeongsangnam-do",
              "ctprvn_cd": "48",
              "ctp_kor_nm": "경상남도"
            },
            "id": "LT_C_ADSIDO_INFO.407"
          },
          {
            "type": "Feature",
            "properties": {
              "ctp_eng_nm": "Jeju-do",
              "ctprvn_cd": "50",
              "ctp_kor_nm": "제주특별자치도"
            },
            "id": "LT_C_ADSIDO_INFO.408"
          }
        ]
      }
    }
  }
}

 

2. api 사용 예제

params는 위와 동일

2.1 광역시도 리스트 가져오기

2.1.1 모든 광역시도 리스트 가져오기

const getSidoAll = async () => {
	cosnt data = await fetchRegionData('req/data?',params);
    return data
}

 

2.1.2 특정 광역시도 정보 가져오기

const getSido = async () => {
	cosnt data = await fetchRegionData('req/data?',{...params,attrfilter: `ctprvn_cd:like:${selectedSido}`});
    return data
}

 

2.2 시군구 리스트 가져오기

2.2.1  모든 시군구 리스트 가져오기

const getSigoonAll = async () => {
	cosnt data = await fetchRegionData(
        'req/data?',
        {...params,data:'LT_C_ADSIGG_INFO'}
    );
    return data
}

2.2.2 특정 시군구 정보 가져오기

const getSigoon = async () => {
	cosnt data = await fetchRegionData(
        'req/data?',
        {...params,data:'LT_C_ADSIGG_INFO',attrfilter:`sig_cd:like:${selectedSigoon}`}
    );
    return data
}

2.2.2  특정 시도 내의 시군구 리스트 가져오기

const getSigoonInSido = async () => {
	cosnt data = await fetchRegionData(
        'req/data?',
        {...params,data:'LT_C_ADSIGG_INFO',attrfilter:`sig_cd:like:${selectedSido}`}
    );
    return data
}

 

2.3 특정 시군구의 읍면동 리스트 가져오기

2.3.1 모든 읍면동 리스트 가져오기

const getDongAll = async () => {
	cosnt data = await fetchRegionData(
        'req/data?',
        {...params,data:'LT_C_ADEMD_INFO'}
    );
    return data
}

 

2.3.2 특정 읍면동 정보 가져오기

const getDong = async () => {
	cosnt data = await fetchRegionData(
        'req/data?',
        {...params,data:'LT_C_ADEMD_INFO',attrfilter:`emd_cd:like:${selectedDong}`}
    );
    return data
}

2.3.3 특정 시군구 내의 읍면동 리스트 가져오기

const getDongInSigoon = async () => {
	cosnt data = await fetchRegionData(
        'req/data?',
        {...params,data:'LT_C_ADEMD_INFO',attrfilter:`emd_cd:like:${selectedSigoon}`}
    );
    return data
}