TIL 40. 2024-02-23

이준구·2024년 2월 23일
0

TIL 순서

목록 보기
40/119
post-thumbnail

outsourcing 프로젝트

  1. 카카오 지도 API 연동
import { Map, MapMarker } from 'react-kakao-maps-sdk';
import { useState, useEffect } from 'react';
import useInput from '../hooks/useInput';

function Location() {
  const [info, setInfo] = useState();
  const [markers, setMarkers] = useState([]);
  const [map, setMap] = useState();
  const [input, onChangeInputHandler] = useInput();

  useEffect(() => {
    //<MAP> 컴포너트 생성 시 실행
    if (!map) return;

    //장소 및 지역 검색
    const ps = new kakao.maps.services.Places();

    ps.keywordSearch(`강남 맛집`, (data, status, _pagination) => {
      //장소 검색이 정상적으로 호출 되었을 때
      if (status === kakao.maps.services.Status.OK) {
        // 검색된 장소 위치를 기준으로 지도 범위를 재설정하기위해
        // LatLngBounds 객체에 좌표를 추가합니다
        const bounds = new kakao.maps.LatLngBounds();
        let markers = [];

        for (var i = 0; i < data.length; i++) {
          //마커스에 검색된 정보 추가
          markers.push({
            position: {
              lat: data[i].y,
              lng: data[i].x
            },
            content: data[i].place_name
          });
          // 검색된 결과의 정보를 지도 범위에 추가
          bounds.extend(new kakao.maps.LatLng(data[i].y, data[i].x));
        }

        //지도에 표시된 마커스 상태 변경
        setMarkers(markers);

        // 검색된 장소 위치를 기준으로 지도 범위를 재설정합니다
        map.setBounds(bounds);
      }
    });
  }, [map]);

  return (
    <StSection>
      <Map // 로드뷰를 표시할 Container
        center={{
          lat: 37.566826,
          lng: 126.9786567
        }}
        style={{
          width: '100%',
          height: '100%'
        }}
        level={3}
        onCreate={setMap}
      >
        {markers.map((marker) => (
          <MapMarker
            key={`marker-${marker.content}-${marker.position.lat},${marker.position.lng}`}
            position={marker.position}
            onClick={() => setInfo(marker)}
          >
            {info && info.content === marker.content && <div style={{ color: '#000' }}>{marker.content}</div>}
          </MapMarker>
        ))}
      </Map>
    </StSection>
  );
}

export default Location;

const StSection = styled.section`
  width: 60%;
  height: 100%;
  background-color: purple;
`;

profile
개발 중~~~ 내 자신도 발전 중😂🤣

0개의 댓글

관련 채용 정보