본문 바로가기
Library-Framework/React

[React] React에서 Google Map API 사용하기 & Polygon 그리기

by 그랴 2023. 2. 19.

구현해야 했던 기능

사용자로부터 입력받은 4개의 지점 값에 해당하는 지역의 위성 지도를 보여주고, 그 경계를 표시해주기


Google Maps API 사용하기

Google Maps API를 사용하면 손쉽게 지도를 불러올 수 있다.

한 달에 28,500번 정도는 무료로 호출 가능하다.

https://developers.google.com/maps?hl=ko 

 

Google Maps Platform  |  Google Developers

Google Maps Platform 설명

developers.google.com

위 사이트에 들어가서 시작하기 버튼을 누른 후, 가입하여 API 키를 받으면 된다.

Docs에서 여러 가지 API에 대한 정보 및 사용 방법들을 확인할 수 있다.

 


React Google Maps 라이브러리 사용하기

Google Maps API Docs가 JavaScript 기준으로 작성이 되어 있기 때문에, React 프로젝트에 바로 적용하기에는 약간 맞지 않는다. (물론 공들여서 Docs를 읽는다면 할 수 있다.)

 

나는 react-google-map 라이브러리를 사용했다.

https://www.npmjs.com/package/@react-google-maps/api 

 

사용방법은 다음과 같다.

1. 설치하기 npm i @react-google-maps/api

2. 코드 작성하기

import React from 'react'
import { GoogleMap, useJsApiLoader } from '@react-google-maps/api';

const DrawMap = () => {
	// API 키
    const { isLoaded } = useJsApiLoader({
    	id: "google-map-script",
    	googleMapsApiKey: process.env.REACT_APP_GOOGLEMAP_API_KEY,
  	});
    
    // 지도 크기
    const containerStyle = {
    	width: "80%",
    	height: "30rem",
  	};
    
    // 지도 중심
    const center = {
    	lat: 20.466,
    	lng: -70.268,
  	};
    
    // 지도 불러오기
    const [map, setMap] = useState(null);

 	const onLoad = useCallback(function callback(map) {
    	const bounds = new window.google.maps.LatLngBounds(center);
    	setMap(bounds);
  	}, []);

  	const onUnmount = useCallback(function callback(map) {
    	setMap(null);
  	}, []);

	return(
    	<>
        {isLoaded ? (
                  <>
                    <GoogleMap
                      mapContainerStyle={containerStyle}
                      center={center}
                      onLoad={onLoad}
                      onUnmount={onUnmount}
                      zoom={13}
                    ></GoogleMap>
                  </>
                ) : null}
        </>
    )


}

위성 지도 기본으로 불러오기

Google Maps API는 다양한 종류의 지도 유형을 지원해준다.

https://developers.google.com/maps/documentation/javascript/maptypes?hl=ko 

 

지도 유형  |  Maps JavaScript API  |  Google Developers

의견 보내기 지도 유형 컬렉션을 사용해 정리하기 내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요. 플랫폼 선택: Android iOS 자바스크립트 이 문서에서는 Maps JavaScript API를 사용하여 표시

developers.google.com

이 때 아무것도 설정을 해주지 않는다면, 기본 지도(카카오맵 같은...)로 띄워준다.

나는 위성 지도를 띄워줘야 했으므로, GoogleMap 컴포넌트 내에 mapTypeId를 satelite로 명시해주었다.

...

        {isLoaded ? (
                  <>
                    <GoogleMap
                      mapContainerStyle={containerStyle}
                      center={center}
                      onLoad={onLoad}
                      onUnmount={onUnmount}
                      zoom={13}
                      mapTypeId='satelite' // 지도 유형
                    ></GoogleMap>
                  </>
                ) : null}
        </>
    )


}

Zoom level

Google Maps API 내에서 사용할 수 있는 Zoom level은 연속적이지 않고 단계별로 나누어져 있다.

참고해서 자신의 프로젝트에 맞는 Zoom level을 설정하면 될 것 같다.

  • 1 : 세계
  • 5 : 대륙
  • 10 : 도시
  • 15 : 거리
  • 20 : 건물

다각형 그리기

GoogleMap 컴포넌트 내부에 Child Component로 Polygon을 추가하여 다각형을 그릴 수 있다.

import React from 'react'
import { GoogleMap, useJsApiLoader } from '@react-google-maps/api';

const DrawMap = () => {
	...
    // 다각형 꼭짓점 정보
     const paths = [
    	{ lat: 20.466, lng: -70.19 },
    	{ lat: 20.466, lng: -80.19 },
    	{ lat: 18.466, lng: -80.19 },
    	{ lat: 18.466, lng: -70.19 },
  	];
    
    // 다각형 스타일
    const options = {
    	fillColor: "white",
    	fillOpacity: 0,
    	strokeColor: "red",
    	strokeOpacity: 1,
    	strokeWeight: 2,
  	};

	return(
    	<>
        {isLoaded ? (
                  <>
                    <GoogleMap
                      mapContainerStyle={containerStyle}
                      center={center}
                      onLoad={onLoad}
                      onUnmount={onUnmount}
                      zoom={13}
                      mapTypeId = 'satelite'
                    >
                    	<Polygon
                        	path={paths}
                        	options={options}
                     	/>
                    </GoogleMap>
                  </>
                ) : null}
        </>
    )


}