-
next.js 에 kakao map 띄우기 (feat. react-kakao-maps-sdk)FrontEnd/Next.js 2024. 2. 6. 15:31
카카오 개발자 센터에 들어가보면 api key (자바스크립트 키) 를 발급 후 아래 코드를 삽입하라고 한다.
<script type="text/javascript" src="//dapi.kakao.com/v2/maps/sdk.js?appkey=발급받은 APP KEY를 넣으시면 됩니다."></script>
"API를 로딩하는 스크립트 태그는 HTML파일안의 head, body 등 어떠한 위치에 넣어도 상관없습니다.
하지만, 반드시 실행 코드보다 먼저 선언되어야 합니다."리액트 같은 경우에는 intex.html에 작성하면 되고 next.js 같은 경우 layout 같은 곳에 Script 태그를 불러와 삽입하면 된다.
하지만 이 같은 번거로운 작업을 JaeSeoKim 님이 배포하신 라이브러리를 사용하면 비교적 간단하게 처리 할 수 있다.
next.js 같은 경우 example에 따르면 .env 에 아래와 같이 작성해두면 script 문을 따로 작성하는 대신
useKakaoLoader를 통해 api 키 넘겨줄 수있음 ( error와 loading도 받아와서 편안 )
NEXT_PUBLIC_APPKEY=발급받은APPKEY
아래는 react-kakao-maps-sdk 의 라이브러리를 사용해서 기본 맵 생성 코드.
'use client'; import { Map, MapMarker, useKakaoLoader } from 'react-kakao-maps-sdk'; export default function KakaoMap() { const [loading, error] = useKakaoLoader({ appkey: process.env.NEXT_PUBLIC_APPKEY!, // 발급 받은 APPKEY }); if (loading) return <div>Loading</div>; if (error) return <div>Error</div>; return ( <Map level={3} center={{ lat: 33.5563, lng: 126.79581 }} style={{ width: '100%', height: '360px' }} > <MapMarker position={{ lat: 33.55635, lng: 126.795841 }}> <div style={{ color: '#000' }}>Hello World!</div> </MapMarker> </Map> ); }
해당 라이브러리
repo : https://github.com/JaeSeoKim/react-kakao-maps-sdk
docs: https://react-kakao-maps-sdk.jaeseokim.dev/docs
추가로 타입스크립트를 사용한다면
https://github.com/JaeSeoKim/kakao.maps.d.ts 해당 패키지 설치하길 바람
'FrontEnd > Next.js' 카테고리의 다른 글
Form에서 두개 이상의 버튼을 다루기 (feat. server action ) (1) 2024.06.14 인가 서버에서 token 받아오기 (OAuth) feat. NextJs (1) 2024.06.10 [next.js] react-quill 에디터 값을 출력하기 (feat. dangerouslySetInnerHTML ) (1) 2024.01.31 Link , Router 비교 (0) 2023.11.16 [Next.js] 테스트 종류 (0) 2023.09.12