이전 포스팅 ✍️
React+TS에서 Kakao Maps API 사용하기 1. 카카오맵api 키 발급, env 파일 설정
const App = () => {
...
return (
<div id="map" style={{ width: "500px", height: "400px" }}></div>
)
}
⚠️ width, height를 %로 지정하면 안!됨!
카카오맵api 공식문서에선 이와 같이 안내한다
import React, { useEffect } from "react";
const kakao = (window as any).kakao;
const Concept = () => {
useEffect(() => {
const container = document.getElementById("map"); //지도를 담을 영역의 DOM 레퍼런스 호출에서 지정
const options = {
//지도를 생성할 때 필요한 기본 옵션
center: new kakao.maps.LatLng(
37.55699327194725,
126.97267350572926
), //지도의 중심좌표
level: 10, //지도의 레벨(확대, 축소 정도)
};
const map = new kakao.maps.Map(container, options); //지도 생성 및 객체 리턴
}, []);
return (
<>
<div id="map" style={{ width: "500px", height: "400px" }}></div>
</>
);
};
export default Concept;
const kakao = (window as any).kakao;
스크립트로 kakao maps api를 심어서 가져오면 window전역 객체에 들어가게 된다. 그리고 그걸 사용하려면 window에서 kakao객체를 뽑아서 사용하면 된다. <<출처 : https://gingerkang.tistory.com/65 >>
이를 타입스크립트에선 위와 같이 사용했다.
우선, 동적으로 화면 사이즈 구하는 방법
window.innerWidth와 window.innerHeight를 이용하면 된다!
const Concept = () => {
const [innerWidth, setInnerWidth] = useState(window.innerWidth);
const [innerHeight, setInnerHeight] = useState(window.innerHeight);
useEffect(() => {
const resizeListener = () => {
setInnerWidth(window.innerWidth);
setInnerHeight(window.innerHeight);
};
window.addEventListener("resize", resizeListener); //화면 사이즈 변경을 감지한다!!!
const container = document.getElementById("map");
const options = {
center: new kakao.maps.LatLng(
37.55699327194725,
126.97267350572926
),
level: 10,
};
const map = new kakao.maps.Map(container, options);
}, []);
return (
<>
<Layout idx={1}>
<div
id="map"
style={{ width: innerWidth, height: innerHeight - 70 }} //저장한 크기를 이용하면 된다!!!
></div>
</Layout>
</>
);
};
완성!
const newLatLng = new kakao.maps.LatLng(crdnt[0], crdnt[1]);
map.panTo(newLatLng);
지도를 호출하는 useEffect 내에서 새로운 중심좌표를 담는 변수를 지정해두고
panTo 를 이용하여 이동한다.
전체코드
const [crdnt, setCrdnt] = useRecoilState(selectedDistrictCrdnt);
useEffect(() => {
const resizeListener = () => {
setInnerWidth(window.innerWidth);
setInnerHeight(window.innerHeight);
};
window.addEventListener("resize", resizeListener);
const container = document.getElementById("map"); //지도를 담을 영역의 DOM 레퍼런스 호출에서 지정
const options = {
//지도를 생성할 때 필요한 기본 옵션
center: new kakao.maps.LatLng(33.450701, 126.570667), //지도의 중심좌표
level: 5, //지도의 레벨(확대, 축소 정도)
};
const map = new kakao.maps.Map(container, options); //지도 생성 및 객체 리턴
const newLatLng = new kakao.maps.LatLng(crdnt[0], crdnt[1]);
map.panTo(newLatLng);
}, [crdnt]);
useEffect의 deps 배열에 변경되는 값을 저장해두었다.
이용자의 선택에 따라 atom에 저장한 좌표값을 변경시키고 이 변경이 감지되면 useEffect를 재렌더링하는 로직이다.