[NextJS] Google map 사용

2023. 11. 9. 08:28NextJS

Next.js에서는 React와 비슷하지만, 서버사이드 렌더링이나 정적 사이트 생성 등의 추가 기능을 제공합니다. 이 경우 Google Maps를 사용하기 위해 직접 스크립트를 로드하는 방식을 사용할 수 있습니다.

환경 변수를 사용하여 Google Maps API 스크립트를 로드하고 현재 위치에 마커를 표시하며, 2km 반경의 원을 그리는 방법에 대한 예시입니다.

먼저, public 디렉토리에 GoogleMap.js라는 스크립트 파일을 만듭니다

// public/GoogleMap.js

window.initMap = function() {};

function loadScript(src, position, id) {
  if (!window.google) {
    const script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = src;
    script.id = id;
    position.appendChild(script);
  }
}

const src = `https://maps.googleapis.com/maps/api/js?key=${process.env.NEXT_PUBLIC_GOOGLE_MAP_API_KEY}&callback=initMap`;
loadScript(src, document.body, 'google-maps-api');

다음으로는, Next.js 페이지 또는 컴포넌트 내에서 Google Maps API와 인터랙션하는 로직을 다음과 같이 구현합니다.

// pages/index.js 또는 components/MyMapComponent.js

import { useEffect, useRef, useState } from 'react';

const MyMapComponent = () => {
  const mapRef = useRef(null);
  const [map, setMap] = useState(null);

  useEffect(() => {
    // GoogleMap.js 스크립트 로드 기다리기
    window.initMap = initMap;

    // 스크립트가 이미 페이지에 존재하는지 확인
    if (!window.google) {
      const script = document.createElement('script');
      script.src = `https://maps.googleapis.com/maps/api/js?key=${process.env.NEXT_PUBLIC_GOOGLE_MAP_API_KEY}&callback=initMap`;
      script.defer = true;
      document.head.appendChild(script);
    } else {
      initMap();
    }

    return () => {
      window.initMap = null;
    };
  }, []);

  // 지도 초기화
  const initMap = () => {
    if (window.google && !map) {
      navigator.geolocation.getCurrentPosition(function(position) {
        const currentLocation = {
          lat: position.coords.latitude,
          lng: position.coords.longitude
        };

        const map = new window.google.maps.Map(mapRef.current, {
          center: currentLocation,
          zoom: 13
        });

        new window.google.maps.Marker({
          position: currentLocation,
          map: map,
          title: "Your Location"
        });

        new window.google.maps.Circle({
          strokeColor: '#FF0000',
          strokeOpacity: 0.8,
          strokeWeight: 2,
          fillColor: '#FF0000',
          fillOpacity: 0.35,
          map: map,
          center: currentLocation,
          radius: 2000 // 2km
        });

        setMap(map);
      });
    }
  };

  return <div id="map" ref={mapRef} style={{ height: '400px', width: '100%' }} />;
};

export default MyMapComponent;

Google Maps API 스크립트를 로드하고, 사용자의 현재 위치를 가져와서 지도에 마커를 표시하고 2km 반경의 원을 그립니다. useEffect 내에서 스크립트 로딩 상태를 감지하고 지도를 초기화하는 로직을 구현했습니다.

추가로 마커 아이콘을 변경하고 싶을 경우 아래와 같이 구현 가능합니다.

			const customIcon = {
				url: '/images/image/logo.png',
				scaledSize: new google.maps.Size(40, 40), // 마커의 크기를 지정
				origin: new google.maps.Point(0, 0), // 이미지의 시작점 (기본적으로 0,0)
				anchor: new google.maps.Point(20, 20) // 마커의 앵커 포인트를 지정
			}

			new window.google.maps.Marker({
				position: currentLocation,
				map: map,
				title: 'Your Location',
				icon: customIcon
			})

'NextJS' 카테고리의 다른 글

[NextJS] Naver Map Clustering  (0) 2023.11.30
[NextJS] dynamic  (0) 2023.08.03
[NextJS] 빌드 디렉토리 구조  (0) 2023.08.01
[NextJS] getInitialProps 사용법  (0) 2022.08.30