카카오디벨로퍼스에 가서 앱 등록 + 앱 키 받아오기
애플리케이션 추가하기
플랫폼 > Web > 사이트 도메인 > http://localhost:3000 등록
JavaScript 키 받아오기
.env에 Javascript 키 추가하기
VITE_KAKAOMAP_JAVASCRIPT_APP_KEY = 아까 그 앱키
index.html의 head에 카카오맵 script api 가져오기
주의 ! 최상단의 index.html에서 하세요 ..
당연한건데 dist > index.html이 먼저 눈에 띄워서 계속 거기서 해서 에러남 ..
<script
type="text/javascript"
strategy="beforeInteractive"
src="//dapi.kakao.com/v2/maps/sdk.js?appkey=%VITE_KAKAOMAP_JAVASCRIPT_APP_KEY%&libraries=services,clusterer,drawing"
></script>
strategy="beforeInteractive"
을 이용하면 어떤 것 보다도 이 script가 가장 먼저 로드 되어 kakao api가 로딩이 뒤늦게 되어 발생하는 에러를 막을 수 있다.TypeScriptd에 필요한 타입정의 패키지 설치하기
# npm
$ npm install kakao.maps.d.ts --save-dev
# yarn
$ yarn add kakao.maps.d.ts --dev
{
...,
"compilerOptions": {
...,
"types": [
...,
"kakao.maps.d.ts"
]
}
}
Map을 불러오는 컴포넌트 작성
/* eslint-disable @typescript-eslint/no-explicit-any */
import { MutableRefObject, useEffect, useRef } from 'react';
declare global {
interface Window {
kakao: any;
}
}
function Map() {
const mapRef = useRef<HTMLElement | null>(null);
const initMap = () => {
const container = document.getElementById('map');
const options = {
center: new window.kakao.maps.LatLng(37.483034, 126.902435),
level: 2,
};
const map = new window.kakao.maps.Map(container as HTMLElement, options);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(mapRef as MutableRefObject<any>).current = map;
};
useEffect(() => {
window.kakao.maps.load(() => initMap());
}, [mapRef]);
return <div id="map" style={{ width: '500px', height: '400px' }}></div>;
}
export default Map;
잘된다.
%VITE_APPKEY%
이런 식으로 써야한다.