DaumPostcode로 주소 검색 후 위도, 경도까지 구하기
1. DaumPostcode
npm i react-daum-postcode
import DaumPostcode from "react-daum-postcode";
return (
<DaumPostcode
style={{ width: "100%", height: "420px" }}
autoClose={false}
onComplete={(addressData) => {
console.log(addressData);
}}
/>
)
매우 간단하다
하지만 지도 API에 연동 하려면 여기서 경도, 위도를 구해야 한다.
2. 카카오 API
https://apis.map.kakao.com/
사용 전에 API key를 발급 받아야한다.
https://developers.kakao.com/
Kakao Developers
카카오 API를 활용하여 다양한 어플리케이션을 개발해보세요. 카카오 로그인, 메시지 보내기, 친구 API, 인공지능 API 등을 제공합니다.
developers.kakao.com
위 링크에서 애플리케이션 추가 후 신청하면 된다.
일단 카카오 스크립트를 삽입한다.
// layout.tsx
<html lang="en">
<head>
<Script
src={`//dapi.kakao.com/v2/maps/sdk.js?appkey=${JS API KEY}&libraries=services,clusterer&autoload=false`}
strategy="beforeInteractive"
/>
</head>
<body>
...
</body>
</html>
저는 이런 식으로 layout.tsx에 스크립트를 삽입했습니다.
// 카카오맵 로드 상태 체크
useEffect(() => {
const checkKakaoLoad = () => {
if (window.kakao && window.kakao.maps) {
window.kakao.maps.load(() => {
console.log("카카오맵 로드 완료");
});
} else {
// 카카오맵이 아직 로드되지 않았다면 100ms 후 다시 체크
setTimeout(checkKakaoLoad, 100);
}
};
checkKakaoLoad();
}, []);
사용할 컴포넌트에서 로드가 잘 되나 확인한 후
// 주소를 좌표로 변환하는 함수
const getCoordinatesFromAddress = async (address: string) => {
if (!window.kakao || !window.kakao.maps) {
console.error("카카오맵이 아직 로드되지 않았습니다.");
return;
}
const geocoder = new window.kakao.maps.services.Geocoder();
try {
const result = await new Promise((resolve, reject) => {
geocoder.addressSearch(address, (result: any, status: any) => {
if (status === window.kakao.maps.services.Status.OK) {
resolve(result);
} else {
reject(new Error(`주소 검색 실패: ${status}`));
}
});
});
console.log("좌표 변환 결과:", result);
} catch (error) {
console.error("주소 검색 중 오류:", error);
}
};
이런 함수를 하나 만들어주고
아까 작성한 DaumPostcode 컴포넌트에서
import DaumPostcode from "react-daum-postcode";
return (
<DaumPostcode
style={{ width: "100%", height: "420px" }}
autoClose={false}
onComplete={async (addressData) => {
console.log(addressData);
// 주소를 좌표로 변환
await getCoordinatesFromAddress(addressData.address);
}}
/>
)
이런 식으로 주소를 텍스트로 보내면
끝!
'Frontend' 카테고리의 다른 글
Recharts 라이브러리 사용기 (1) | 2025.06.12 |
---|---|
[Next.js 14] NextAuth Server Error - There is a problem with the server configur (0) | 2025.04.18 |
[Next.js 14] NextAuth 적용기 (네이버 로그인, 카카오 로그인, 구글 로그인) (0) | 2025.04.17 |
[Next.js 14] 이미지 성능 개선 , Next/Image CPU 사용량 이슈 , react-lazy-load-image-component 적용기 (0) | 2025.04.16 |