Next.js + typeScript 에서 Leaflet + kakao 검색 API 사용하기

support·2022년 7월 25일
0

Today I Learned

목록 보기
6/11

kakao .places() 공식문서
주소 검색 기능 - 프로젝트 사용시 정리했던 글

1. 스크립트 작성

pages / _document.tsx

export default function Document() {
  return (
    <Html>
      <Head>
    	...
        <script
          type="text/javascript"
          src="//dapi.kakao.com/v2/maps/sdk.js?appkey= 키 발급받아서 넣으세용 &libraries=services"
        ></script>
      </Head>
    </Html>
  );
}

2. global interface 선언

declare global {
  interface Window {
    kakao: any;
  }
}

3. 검색 코드 작성

index.js

import type { NextPage } from "next";

declare global {
  interface Window {
    kakao: any;
  }
}

const Home: NextPage = () => {
  const SearchMap = () => {
    const ps = new window.kakao.maps.services.Places();

    const placesSearchCB = function (data: any[], status: any) {
      if (status === window.kakao?.maps.services.Status.OK) {
        console.log(data);
      }
    };
    ps.keywordSearch("서울", placesSearchCB);
  };
  return (
    <>
      <button onClick={SearchMap}>클릭</button>
    </>
  );
};

export default Home;

받아온 데이터 가공해서 사용하기!

+ debounce

onchange로 데이터를 가져오게 되면 글자가 작성될 때마다 api를 호출하게 된다.
debounce를 사용하면 호출되는 함수 중 마지막이나 처음만 호출할 수 있도록 해서 사용성 향샹과 비용 감소의 효과가 있다.

lodash-es 에서 debounce함수를 제공해주고 있다.

설치

yarn add lodash-es
yarn add --save @types/lodash-es
import { debounce } from "lodash-es";

declare global {
  interface Window {
    kakao: any;
  }
}

const Search = () => {
  const [searchAddress, setSearchAddress] = useState<string>("");
  const [addressResult, setAddressResult] = useState<any[]>();

  const handleSearchAddress = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.currentTarget.value;
    setSearchAddress(value);
    debounceAddress(value); //  ✅ debounce
  };

 const debounceAddress = debounce((item) => {
    SearchMap(item);
  }, 300); //  ✅ debounce

  const SearchMap = (item: string) => {
    const ps = new window.kakao.maps.services.Places();

    const placesSearchCB = function (data: any[], status: any) {
      if (status === window.kakao?.maps.services.Status.OK) {
        setAddressResult(data);
      }
    };
    ps.keywordSearch(`${item}`, placesSearchCB);
  };

  return(
    <div>
      <input
        placeholder="주소 검색"
        onChange={handleSearchAddress}
        autoFocus
        ></input>
    </div>
  )
}

참고
lodash 대신 lodash-es 사용
codeSandBox - lodash 사용 예제

0개의 댓글