해결한 문제
- 다음카카오의 주소 검색 API를 통해 주소를 검색하여 입력기능 추가
- 입력 칸의 submit 시 좌표를 가져오는 코드 순서를 주소 검색 시 좌표를 가져와 입력하도록 수정
// 카카오 API, 주소를 위도 경도로 변환
const callMapcoor = () => {
var geocoder = new window.kakao.maps.services.Geocoder();
var callback = function (result, status) {
if (status === window.kakao.maps.services.Status.OK) {
mapcoor.current.longitude = Math.floor(result[0].x * 100000);
mapcoor.current.latitude = Math.floor(result[0].y * 100000);
console.log("kako map API 이상없음!", mapcoor.current);
}
addUserEvent();
};
geocoder.addressSearch(address.address, callback);
};
기존 코드는 주소를 입력한 후 따로 이벤트를 추가하지 않아(버튼 추가는 사용 시 번거로워 보였음) 좌표를 구하는 API를 구동할 구간이 따로 없어 submit 시 좌표를 구하여 위도와 경도를 저장하는 방식으로 사용하였음.
이 때, 카카오 API가 비동기로 동작하여, 좌표가 mapcoor에 저장되기 전에 submit이 완료되는 오류가 발생하였다.
function submitHandle(){
address ? callMapcoor() : addUserEvent()
}
따라서 위와 같이 코드를 수정하였음.
submit 시 주소값이 있다면 callMapcoor 함수가 동작하고, 입력한 주소가 없다면 submit 이벤트가 동작하도록 설정하여 위와 같이 카카오 API 함수 내에 addUser submit 함수가 동작하도록 하였다.
하지만!!
다음카카오의 우편번호 입력 API를 추가하며 해당 기능을 주소를 검색할 때 좌표를 계산하여 입력하는 것으로 수정을 함께 진행하였다.
참고 링크
다음 우편번호 서비스 가이드 링크
Daum 우편번호 서비스
우편번호 검색과 도로명 주소 입력 기능을 너무 간단하게 적용할 수 있는 방법. Daum 우편번호 서비스를 이용해보세요. 어느 사이트에서나 무료로 제약없이 사용 가능하답니다.
postcode.map.daum.net
사용한 라이브러리
react-daum-postcode
Daum Postcode service for React. Latest version: 3.1.1, last published: 4 months ago. Start using react-daum-postcode in your project by running `npm i react-daum-postcode`. There are 16 other projects in the npm registry using react-daum-postcode.
www.npmjs.com
코드
부모 컴포넌트
// address:신주소, oldaddress:구주소, zipcode:우편번호, longitude:위도, latitude:경도
const [address, setAddress] = useState({});
...
<label htmlFor="address" className=" blockLabel">
주소
</label>
<PieceRegisterSearchPopUp
setAddress={setAddress}
address={address}
getedData={getedData}
/>
자식 컴포넌트
import React from "react";
import { useEffect } from "react";
import { useDaumPostcodePopup } from "react-daum-postcode";
export default function Postcode({ setAddress, address, getedData }) {
// 다음 주소 검색 API 주소
const scriptUrl =
"//t1.daumcdn.net/mapjsapi/bundle/postcode/prod/postcode.v2.js";
// eact-daum-postcode의 popup 방식 사용
const open = useDaumPostcodePopup(scriptUrl);
// 부모 컴포넌트에게 값을 전달하기 위해 함수로 사용
function fnSetAddress(address) {
setAddress(address);
}
// 카카오 API, 주소를 위도 경도로 변환
const callMapcoor = () => {
var geocoder = new window.kakao.maps.services.Geocoder();
var callback = function (result, status) {
if (status === window.kakao.maps.services.Status.OK) {
fnSetAddress({
...address,
latitude: Math.floor(result[0].y * 100000),
longitude: Math.floor(result[0].x * 100000),
});
}
};
geocoder.addressSearch(address.address, callback);
};
useEffect(() => {
// 신주소 : address, 구주소 :oldaddress, 우편번호 : zipcode
fnSetAddress({
address: getedData.address,
oldaddress: getedData.oldaddress,
zipcode: getedData.zipcode,
longitude: getedData.longitude,
latitude: getedData.latitude,
});
}, [getedData.address]);
// 팝업 입력창에 값을 입력하면 작동하는 함수
const handleComplete = (data) => {
// 다음 카카오 신주소 : roadAddress, 구주소 :jibunAddress, 우편번호 : zonecode
// 공사콕에서 사용하는 key와 다음 카카오의 키가 다름!
fnSetAddress({
address: data.roadAddress,
oldaddress: data.jibunAddress,
zipcode: data.zonecode,
longitude: data.longitude,
latitude: data.latitude,
});
// 팝업 입력창에 값을 입력하면 해당 주소로 좌표를 구함
callMapcoor();
};
const handleClick = () => {
open({ onComplete: handleComplete });
};
return (
<>
<input
type="text"
id="roadAddress"
disabled
name="_roadAddress"
value={address.address || ""}
/>
<input
type="text"
id="zoneCode"
name="_zoneCode"
value={address.zipcode || ""}
disabled
/>
<button
type="button"
onClick={handleClick}
style={{ backgroundColor: "red" }}
>
Open
</button>
<div className="formContentWrap">
<label htmlFor="address" className=" blockLabel">
좌표
</label>
<ul className="detailContent" style={{ display: "flex" }}>
<li>
<span>위도</span>
<input type="text" disabled value={address.longitude || ""} />
</li>
<li>
<span>경도</span>
<input type="text" disabled value={address.latitude || ""} />
</li>
</ul>
</div>
</>
);
}
css 수정은 아직 진행되지 않았고, 다시 한 번 전체 css를 변경해야 해 한 번에 진행할 예정입니다.
'front > react' 카테고리의 다른 글
메인 색상 변환 및 레이아웃 수정 및 작업 현황 (0) | 2022.11.16 |
---|---|
[style] 관리자 페이지 navigation 디자인 변경 (0) | 2022.11.01 |
[Feat]필터 검색 추가 (회원관리) (0) | 2022.10.25 |
[react validation] react-hook-form & 정규 표현식 (0) | 2022.10.24 |
[Refactor] onChane, useState에서 react-hook-form의 getValues, setValue로 변경 (0) | 2022.10.21 |