// checkedPlace로 props값 받아오면 useEffect 실행하여 지도에 마커 찍히도록 gettingLocation 함수 실행.
useEffect(() => {
if(checkedPlace) {
gettingLocation(positions)}
},[checkedPlace])
// 키워드 입력후 검색 클릭 시 원하는 키워드의 주소로 이동
const gettingLocation = function (positions) {
// checkedPlace가 오는게 아니라 positions가 와야함. postions가 마커 state 값
const newSearch = checkedPlace;
const prevPositions = [...positions];
setPositions(prevPositions =>[
...prevPositions,
{
title: newSearch.place_name,
latlng: { lat: newSearch.y, lng: newSearch.x },
},
]);
}
return (
<Map
center={center}
style={{ width: '690px', height: '803px', maxWidth:'100%', maxHeight:'100%' }}
>
{positions.map((position, index) => (
<MapMarker
key={index}
position={position.latlng} // 마커를 표시할 위치
image={{
src: 'https://t1.daumcdn.net/localimg/localimages/07/mapapidoc/markerStar.png', // 마커이미지의 주소입니다
size: {
width: 24,
height: 35,
}, // 마커이미지의 크기입니다
}}
title={position.title} // 마커의 타이틀, 마커에 마우스를 올리면 타이틀이 표시됩니다
/>
))}
)
다중 마커가 안 찍힌다. 계속 하나만 찍힌다. 아무리 코드 수정해보고 이것저것 추가해보고 삭제해보고 해도 안 된다. 마커를 찍는 부분이 어떤건지 콘솔찍어보고 하나하나 실행해보며 알아내었다.
// 키워드 입력후 검색 클릭 시 원하는 키워드의 주소로 이동
const gettingLocation = function (positions) {
// checkedPlace가 오는게 아니라 positions가 와야함. postions가 마커 state 값
const newSearch = checkedPlace;
const prevPositions = [...positions];
setPositions(prevPositions =>[
...prevPositions,
{
title: newSearch.place_name,
latlng: { lat: newSearch.y, lng: newSearch.x },
},
]);
}
이 부분에서 마커를 찍어주는 로직이 있다. 그 중에서 checkedPlace의 state 값이 없으면 마커를 찍어주지 못하고 있다. 이 부분이 문제인데, 이 부분을 어떻게 수정해보면 좋을까?
checkedPlace state값을 못 들고 오는게 문제가 아니였다. checkedPlace는 이미 위에서 서버와 통신을 위해서 x,y값을 배열로 만들어 state값들을 저장하고 있었다. 아래와 같이 말이다.
// x,y값이 추가 되어도 같은 값이 x2,y2로 들어가는 버그 수정 코드
let newCheckedPlace = { ...checkedPlace, [currentInputIndex === 0 ? 'x' : `x${currentInputIndex + 1}`]: x, [currentInputIndex === 0 ? 'y' : `y${currentInputIndex + 1}`]: y };
// setCheckedPlace함수 서버 통신위하여 가공
setCheckedPlace(newCheckedPlace);
그래서 처음에 x,y값만 제대로 들어가고, 두번째 값부터는 가공이 되면서 제대로 마커를 찍는 좌표를 주지 못하고 있었던 것이다. 그러면 Postions를 사용? positions는 출발지 1,2,3,4의 좌표값들을 하나하나 차곡차곡 담아줘야한다.
그렇다면 state값을 하나 더 만들어줘 검색이 될 때 마다 positions값에 넣어 map으로 돌려주면 되겠다.
그래서 state 추가
// 모달창 검색값 있는 그대로 배열로 만들어주는 state 값(다중마커위한)
const [checkedMarkerPlace, setCheckedMarkerPlace] = useState([]);
드디어 마커 여러개 정상적으로 찍기 완료
수정된 코드 일부
function checkedPlaceHandler(place) {
// checkedPlace 객체를 request 폼으로 가공
const { x, y } = place;
console.log("place",place)
// x,y값 undefined일 시 조건문
if (!x || !y) {
console.error('Invalid place object:', place);
return;
}
// place 매개변수 받아 모달창 props의 좌표값 받아서 지도 옮겨줌.
setCenter({ lat: y, lng: x });
// 인풋박스 각각의 값에 각각의 props state값 주는 로직.
const newInputValues = [...inputValues];
newInputValues[currentInputIndex] = place.place_name;
setInputValues(newInputValues);
// x,y값이 추가 되어도 같은 값이 x2,y2로 들어가는 버그 수정 코드
let newCheckedPlace = { ...checkedPlace, [currentInputIndex === 0 ? 'x' : `x${currentInputIndex + 1}`]: x, [currentInputIndex === 0 ? 'y' : `y${currentInputIndex + 1}`]: y };
// setCheckedPlace함수 서버 통신위하여 가공
setCheckedPlace(newCheckedPlace);
// positions state에 검색된 state값 차곡차곡 담기위한 다중마커state값
setCheckedMarkerPlace(place)
}
이번에도 콘솔의 중요성을 정말 뼈저리게 느꼈다. 자꾸 밖에서 딴데서, 뭔가 신박한 추가되는 코드를 찾지말자. 정말 콘솔 한땀한땀 하나씩 찾고, 거기서 데이터가 어떻게 흘러가고 어떻게 가공해서 사용할 지, 정말 기본을 잘 생각하고 따르자. 결국에는 역시나 기본이 제일 중요하다. 다시 한 번 깨달았다.
그렇지만 마커가 장소 선택 바뀌어도 삭제되지 않고 그대로 남아있는 버그 발견. 이 부분 수정 필요.