React, TS, Vite 환경에서 카카오맵 띄우기

  1. 카카오디벨로퍼스에 가서 앱 등록 + 앱 키 받아오기
- 플랫폼 > Web > 사이트 도메인 > [http://localhost:3000](http://localhost:3000) 등록

- JavaScript 키 받아오기

  ![](https://velog.velcdn.com/images/hyorish03/post/a7fbfa50-e75f-4208-80f1-cf9aec81980b/image.png)
  1. .env에 Javascript 키 추가하기
```jsx
VITE_KAKAOMAP_JAVASCRIPT_APP_KEY = 아까 그 앱키
```
  - env가 뭔지 모르면 [ENV 알아보기](https://velog.io/@hyorish03/ReactNative-env%EB%9E%80)
  1. 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가 로딩이 뒤늦게 되어 발생하는 에러를 막을 수 있다.
  2. TypeScriptd에 필요한 타입정의 패키지 설치하기

    • https://github.com/JaeSeoKim/kakao.maps.d.ts

        # npm
        $ npm install kakao.maps.d.ts --save-dev
      
        # yarn
        $ yarn add kakao.maps.d.ts --dev
    • tsconfig.json의 compilerOptions.types 속성에 패키지 추가

        {
          ...,
          "compilerOptions": {
            ...,
            "types": [
              ...,
              "kakao.maps.d.ts"
            ]
          }
        }
  3. 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;

잘된다.

웹뷰로 지도 띄우는데..

  • 완전 멍충한 짓 함
  • index.html이 dist 내에 하나 그냥 하나 있는데 dist (배포용 폴더)에 있는 index.html에 script 태그 넣어두고 에러난다고 찡찡찡거림
  • 1시간 30분만에 원인을 알아버렸습니다..

새로 배운 것

  • index.html에서 env 변수를 쓰려면 %VITE_APPKEY% 이런 식으로 써야한다.
  • 소스코드에서 쓰는 것처럼 import.meta.env 하면 안 됨

+ Recent posts