[React] react-google-map/api GoogleMap/MarkerF/InfoWindowF 사용

상교·2023년 2월 21일
1

@react-google-map/api 을 이용해보자.

0. 라이브러리 설치

https://www.npmjs.com/package/@react-google-maps/api
위 라이브러리 문서에 기본적인 설치법과 예제 코드가 올라와 있다.

npm i -S @react-google-maps/api

1. API key 발급받기.

https://devkkiri.com/post/2a105ee2-112e-4d15-9dc0-a3a7b6f2adcf
구글 맵을 개인이 이용하더라도 결제 수단을 등록해야 API key를 발급받을 수 있다. 위 블로그를 참고해 키를 발급받아야 google map을 사용할 수 있다.

2. 기본 지도 예제

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

const containerStyle = {
  width: '400px',
  height: '400px'
};

const center = {
  lat: -3.745,
  lng: -38.523
};

function MyComponent() {
  const { isLoaded } = useJsApiLoader({
    id: 'google-map-script',
    googleMapsApiKey: "YOUR_API_KEY"
  })

  const [map, setMap] = React.useState(null)

  const onLoad = React.useCallback(function callback(map) {
    // This is just an example of getting and using the map instance!!! don't just blindly copy!
    const bounds = new window.google.maps.LatLngBounds(center);
    map.fitBounds(bounds);

    setMap(map)
  }, [])

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

  return isLoaded ? (
      <GoogleMap
        mapContainerStyle={containerStyle}
        center={center}
        zoom={10}
        onLoad={onLoad}
        onUnmount={onUnmount}
      >
        { /* Child components, such as markers, info windows, etc. */ }
        <></>
      </GoogleMap>
  ) : <></>
}

export default React.memo(MyComponent)

useJsApiLoader 부분에 본인이 발급받은 key를 입력하면 기본 지도 띄우기까지는 성공이다. 쉽죠?

3. 지도 커스텀하기

공식 문서에 간단한 사용법이 나와 있긴 하지만, 지도를 원하는 모습으로 커스텀하기에는 정보가 부족하다.

3-1. 기본 UI 지우기

기본 지도에는 거추장스러운 UI가 많이 달려있다. 깔끔한 디자인을 위해서 지워주자.

<GoogleMap 
	...
    options={{disableDefaultUI: true}}
    ...
    >
</GoogleMap>

disableDefaultUI: true 를 GoogleMap의 options 에 추가해주면 기본 UI가 사라진다.

3-2. 기본 마커 지우기

구글맵에는 기본적으로 명소, 음식점, 버스정류장 등의 수많은 마커가 떠 있어서 지저분하다. 이것도 지워주자.

const myStyles = [
  {
    featureType: "poi",
    elementType: "labels",
    stylers: [{ visibility: "off" }],
  },
];
...
<GoogleMap 
	...
    options={{ disableDefaultUI: true, styles: myStyles }}
    ...
    >
</GoogleMap>

위와 같이 options에 styles 옵션을 설정해주면 지저분한 마커들을 모두 없애 버릴 수 있다.

3.3. 커스텀 마커 추가하기

!! React 18 이후 버전에서는 Marker 대신 MarkerF 를 사용해야 한다. 이것 때문에 한참 고생함 ㅠㅠ

<GoogleMap>
	...
	<MarkerF
		onLoad={onLoad}
		position={{ lat: 위도 , lng: 경도 }}
        icon={{
        	url: "icon.svg",
        	scaledSize: new window.google.maps.Size(32, 32),
		}}
	/>
	...
<GogleMap />

positionlatlng 에 위도, 경도를 추가하면 해당 위치에 기본 빨간 마커가 추가된다.
이때 아이콘을 변경하고 싶다면 본인이 원하는 아이콘의 경로와 사이즈를 icon 에 넣어주면 된다.

3.4 마커에 InfoWindow 추가하기

마커를 클릭하면 작은 정보창이 나오도록 해보자. 마찬가지로 React 18 이후로는 InfoWindowF 를 사용해야 한다.

const [selectedMarker, setSelectedMarker] = useState(null);
...
<MarkerF
	onLoad={onLoad}
	position={{ lat: 위도 , lng: 경도 }}
	icon={{
      url: "icon.svg",
      scaledSize: new window.google.maps.Size(32, 32),
		}}
    onClick={(e) => {
    	setSelectedMarker({ lat: 위도, lng: 경도 });
        setCenter({ lat: 위도, lng: 경도  });
/>
<InfoWindowF
	position={selectedMarker}
    options={{ pixelOffset: new window.google.maps.Size(0, -25) }}
    onCloseClick={() => {
            setSelectedMarker(null);
          }}
>
<div>
  <h1> info </h1>
</div>
  
  • MarkerF의 onClick 시에 setCenter 함수를 설정하도록 하면 마커를 클릭할 때 해당 마커의 위치로 지도 중심이 이동하게 된다.
  • options의 pixelOffset 을 통해서 마커가 뜨는 위치를 조절할 수 있다. 기본값은 마커가 찍힌 위치에 뜨기 때문에 마커가 가려지는데, 위 코드를 이용하면 마커의 중심에 정보창이 뜬다.

여러 마커를 찍을 경우에는 map 함수와 useState를 조합해서 여러 정보를 정보창에 띄우도록 할 수 있다.


@react-google-maps/api 의 경우에는 공식 문서가 불친절하고, 구글링해도 정보가 잘 나오지 않아 세세한 설정이 살짝 귀찮았다. 그래도 다른 지도들과 다르게 다른 나라에서도 정상적으로 작동한다는 장점이 있다.

profile
편안함에 안주하지 않는 프론트엔드 개발자입니다.

0개의 댓글