5월3일(수) 드디어! 마커 버그 해결

Mindfulness·2023년 5월 2일

드디어 정확한 마커 지워지고 주소값 바꿔도 기존 마커 지워지며 정확한 마커 이동 된다. 정말..... 너무 기뻤다.. 이게 얼마만에 뚫는 버그인가..

샤워하다가 문득 떠올랐다. 지금까지 너무 어렵게 생각하고 있었던 거 같다. 카카오 API이용하려하고 어려운 조건문들 추가하고 등등. 근데 콘솔로 한땀 한땀 데이터 분석하니 일단 postions (마커찍어주는 배열 state)이 inputValues 라는 인풋값의 값이 변경될 때 같이 업데이트가 안 되었다. 근본적인 원리다. 이 부분 오늘 5시간정도 끙끙대다 다른 버그도 없이 깔끔히 구현되었다.

코드는 아래와 같다.

//  자식 컴포넌트 props 꺼내서 쓸 수 있도록 한다.
  function checkedPlaceHandler(place) {
    // checkedPlace 객체를 request 폼으로 가공
    const { x, y } = 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];
    // 인풋 박스 안에 넣을 값중 키워드이름 + (주소). 그중 도로명 주소가 없다면 지번 주소로 입력되도록 placeAddress선언
    const placeAddress = place.road_address_name || place.address_name;
    //  인풋 박스에 키워드이름(주소이름) 적히도록 수정.
    newInputValues[currentInputIndex] = `${place.place_name} (${placeAddress})`;
    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값 (place는 모달창에서 검색 및 선택된 값)
    setCheckedMarkerPlace(place);
    console.log("newInputValues",newInputValues)
    console.log("inputValues",inputValues)
    -------------------------------------------------
    // positions 업데이트 추가부분 (정확히 원하는 마커 지워 지도록 positions값 currentInputIndex 같이 엮어서 업데이트 해줌. 매우 중요)
    const newPositions = [...positions];
    newPositions[currentInputIndex] = {
      title: place.place_name,
      latlng: { lat: place.y, lng: place.x },
    };
    setPositions(newPositions);
    --------------------------------------------------
    }
 //  X버튼 핸들러(inputValue 초기화)
  const onInputClearHandler = (index) => {
    const newInputValues = [...inputValues];
    newInputValues[index] = '';
    setInputValues(newInputValues);
--------------------------------------------------------
    // positions 업데이트 (정확한 해당 마커 지워지도록 positions 업데이트 코드 추가)
  const newPositions = [...positions];
  newPositions[index] = undefined;
  setPositions(newPositions);
---------------------------------------------------
    let newCheckedPlace = {
      ...checkedPlace,
      [index === 0 ? 'x' : `x${index + 1}`]: undefined,
      [index === 0 ? 'y' : `y${index + 1}`]: undefined,
    };
    setCheckedPlace(newCheckedPlace);
  };
{positions?.map((position, index) => (
				
   추가된 부분->   inputValues[index] && (
                
                  <MapMarker
                    key={index}
                    position={position?.latlng}
                    image={{
                      src: 'MarkerIMG.png',
                      size: {
                        width: 38,
                        height: 50,
                      },
                    }}
                    title={position?.title}
                  />
                )
              ))}

코드설명~

너무 어렵게 생각하지 말고, 뭔가 특별한 거를 생각하지 말자. 정말 있는 거기서 깊이 파고들어가보고 가장 안쪽의 기본적인 부분에 대해 고민해보고 확장해가자. 지금 생각해보면 해당 문제 어렵지 않은 문제인데 왜 이렇게 빙 둘러서 왔지 하는 생각이 든다.

profile
Junior Frontend Developer

0개의 댓글