React 카카오맵 API

H_Chang·2023년 12월 6일
1

카카오맵 API

  • 이번에 카카오맵 API를 이용한 아웃소싱 팀 프로젝트를 시작했다.
  • 카카오맵 API 같은 경우는 한국어기 때문에 문서를 보더라도 매우 쉽게 이해하면서 코드를 작성할 수 있다.

공식 홈페이지 : https://apis.map.kakao.com/web/guide/
문서: https://apis.map.kakao.com/web/documentation/

사용해보기

우선, 나는 리액트를 사용하고 있기 때문에 최대한 리액트스럽게 만들어보려했다. 그래서 이번에도 custom Hook을 만들었다. 그리고 Map이라는 컴포넌트를 만들어서 사용했다

코드

useFetchMap.js

import { useEffect, useRef } from "react";

const { kakao } = window;

const useFetchMap = (latitude, longitude) => {
  const container = useRef(null);

  useEffect(() => {
    kakao.maps.load(() => {
      const center = new kakao.maps.LatLng(latitude, longitude);
      const options = {
        center,
        level: 4,
      };
      const map = new kakao.maps.Map(container.current, options);

      const markerPosition  = new kakao.maps.LatLng(latitude, longitude); 

      const marker = new kakao.maps.Marker({
          position: markerPosition
      });

      marker.setMap(map);
    });
  }, [latitude, longitude]);

  return { container };
};

export default useFetchMap;

코드는 위와 같다. 우선 전역 객체 kakao다. 이 객체는 window 에서 가져오고 카카오맵 API에서 제공하는 기능을 포함하고 있다.

다음으로 useFetchMap 함수는 경위선을 매개변수로 받는다. 그리고 useRef를 사용해서 지도를 렌더링할 DOM 요소에 대한 참조(ref)를 생성한다. 처음에는 null로 아무것도 참조하지 않는다.

마지막으로 Map이 들어있는 container를 반환하면 끝이다.

Map.jsx

import React from "react";
import useFetchMap from "../../../hooks/useFetchMap";

const lat = 위도;
const lon = 경도;

const Map = () => {
  const { container } = useFetchMap(lat, lon);

  return (
    <div
      ref={container}
      style={{ width: "1265px", height: "350px", border: "1px solid black" }}
    />
  );
};

export default Map;

마지막으로 Map 컴포넌트에서 useFetchMap 함수를 가져와 위도와 경도를 넣어주고, div에 참조할 수 있게 하면 끝난다.

profile
프론트 엔드 시작하는 뉴비!

0개의 댓글