React+Mapbox 초기 세팅 🌍

2025. 3. 4. 23:35·Dev

Mapbox를 통해 GeoJSON 데이터를 테스트하기 위하여 React와 Mapbox를 연동하는 세팅을 진행하였다.

 

1️⃣ Create a React App with Vite

1.  Vite를 사용하여 React 프로젝트를 생성한다.

$ npm create vite@latest 'mapbox-react'

 

 

2. npm 모듈을 설치하고 실행한다.

$ cd mapbox-react
$ npm install
$ npm run dev

 

3. http://localhost:5173/ 에 접속하면 다음과 같은 화면이 나타난다. 🎉

2️⃣ Create a map container element

1. Mapbox GL JS는 특정 HTML요소(div)에 맵을 추가하는 방식으로 동작한다. 이를 맵 컨테이너라고 하며, 크기와 위치를 CSS로 지정해야 한다.

 

📌 src/App.tsx 수정:

import './App.css'

function App() {
  return (
    <>
      <div id='map-container' />
    </>
  )
}

export default App

 

📌 src/App.css 수정:

#root {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}

#map-container {
  height: 100%;
  width: 100%;
  /* temporarily set the background color so we can tell where the map container is positioned */
  background-color: lightgrey;
}

.sidebar {
  background-color: rgb(35 55 75 / 90%);
  color: #fff;
  padding: 6px 12px;
  font-family: monospace;
  z-index: 1;
  position: absolute;
  top: 0;
  left: 0;
  margin: 12px;
  border-radius: 4px;
}

.reset-button {
  position: absolute;
  top: 50px;
  z-index: 1;
  left: 12px;
  padding: 4px 10px;
  border-radius: 10px;
  cursor: pointer;
}

 

📌 src/index.css 내용 삭제: (맵 컨테이너의 스타일을 방해하지 않도록)

/* index.css should be empty */

 

3️⃣ Add a Mapbox GL JS Map

📌 Mapbox GL 패키지 설치:

$ npm install mapbox-gl

 

📌 src/App.tsx 수정

    • useRef hook 2가지
      • mapRef: 맵 인스턴스 유지, 이 컴포넌트의 lifecycle동안 맵 제어
      • mapContainerRef: 컨테이너의 HTML 요소를 노출하여 맵을 생성할 위치를 Mapbox GL JS에 알려줌
    • 여기서 Access Token은 mapbox 홈페이지에서 할당받아 작성해준다.
import { useRef, useEffect } from 'react';
import mapboxgl from 'mapbox-gl';
import 'mapbox-gl/dist/mapbox-gl.css';
import './App.css';

function App() {
  const mapRef = useRef<mapboxgl.Map | null>(null); // 맵 인스턴스 참조
  const mapContainerRef = useRef<HTMLDivElement | null>(null); // 맵 컨테이너 참조

  useEffect(() => {
    mapboxgl.accessToken = 'YOUR_MAPBOX_ACCESS_TOKEN'; // 🔑 Mapbox Access Token 입력
    mapRef.current = new mapboxgl.Map({
      container: mapContainerRef.current as HTMLDivElement,
      center: [0, 0], // 🌎 초기 지도 위치 (경도, 위도)
      zoom: 2, // 🔍 초기 줌 레벨
    });

    return () => {
      mapRef.current?.remove(); // 컴포넌트 언마운트 시 맵 제거
    };
  }, []);

  return (
    <>
      <div id='map-container' ref={mapContainerRef} />
    </>
  );
}

export default App;

 

그럼 아래와 같은 화면이 뜬다! 🎉

 

참고

Use Mapbox GL JS in a React app

'Dev' 카테고리의 다른 글

직접 써본 FSD (Feature-Sliced Design) 적용기: 깔끔함과 혼란 사이  (0) 2025.04.05
[OAuth] OAuth 2.0을 파헤쳐보자 🔍 + 소셜로그인 예제  (0) 2025.03.05
[OAuth] GCP (Google Cloud Platform)에서 Client ID 생성하기 🪪  (0) 2025.03.05
[OAuth] OAuth란? 🤔  (0) 2025.03.04
React+MapBox Geojson 올리기 (Height 속성 활용하기 )  (0) 2025.03.04
'Dev' 카테고리의 다른 글
  • [OAuth] OAuth 2.0을 파헤쳐보자 🔍 + 소셜로그인 예제
  • [OAuth] GCP (Google Cloud Platform)에서 Client ID 생성하기 🪪
  • [OAuth] OAuth란? 🤔
  • React+MapBox Geojson 올리기 (Height 속성 활용하기 )
Lucy96
Lucy96
개발새발 프론트엔드 개발자
  • Lucy96
    Lucy dev ✨
    Lucy96
  • 전체
    오늘
    어제
    • 분류 전체보기 (18)
      • JavaScript (3)
      • React (1)
      • HTTP (1)
      • GIS (1)
      • 회고 (3)
      • Dev (7)
      • CSS (1)
      • DB (1)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

    • github
  • 공지사항

  • 인기 글

  • 태그

    자바스크립트엔진
    회고
    cors
    소셜로그인
    BEM
    gcp
    localStorage
    geojson
    논블로킹
    Hoisting
    콜백큐
    Cookie
    CSS
    HTTP
    프론트엔드
    이벤트루프
    webapis
    react
    블로킹
    sessionStorage
    토스
    Mapbox
    JavaScript
    토스모닥불
    scss
    oauth
    Google Cloud Platform
    OAuth 2.0
    scope
    cliend id
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Lucy96
React+Mapbox 초기 세팅 🌍
상단으로

티스토리툴바