[TIL] 230718

이세령·2023년 7월 18일
0

TIL

목록 보기
58/118

Kakao map api

주소에 따른 좌표값 가져오기

주소에 따라 위치를 표기하기 위해서 주소를 입력하여 위도, 경도를 얻어올 수 있다.

const geocoder = new kakao.maps.services.Geocoder();

    const callback = function (result, status) {
      if (status === kakao.maps.services.Status.OK) {
        console.log('주소', result[0]);
        setX(result[0].x);
        setY(result[0].y);
      }
    };
    geocoder.addressSearch('제주특별자치도 서귀포시 안덕면 사계남로84번길 4 1층', callback);

마커 표기하기


위에서 set한 좌표에 따라 마커위치를 넣어주고 중앙값도 표기해준다.

useEffect(() => {
    // 좌표 찾기
    findCoordinates();

    // map 세팅하기
    const container = document.getElementById('map');
    const options = {
      center: new kakao.maps.LatLng(y, x),
      level: 3
    };
    const map = new kakao.maps.Map(container, options);

    // 마커 표시하기
    const markerPosition = new kakao.maps.LatLng(y, x);
    const marker = new kakao.maps.Marker({
      position: markerPosition
    });
    marker.setMap(map);

    setMap(map);
    console.log(x, y);
  }, [x, y]);

데이터를 찍어보면 위도와 경도가 y, x이기 때문에 반대로 값을 넣어주어야 정상 동작이 가능하다.
좌표 값에 따라 렌더링 되어야 하기 때문에 의존성 배열에 좌표값을 넣어주었다.

리스트 필터링


위 사진처럼 리스트를 필터링 할 수 있게 필터링 해주는 코드 커스텀 훅으로 작성해주었다.

import { useEffect, useState } from 'react';

const usePlaceData = (list, area, category) => {
  const [dataList, setDataList] = useState([]);

  const filterTour = (data) => {
    const a = data.filter((item) => {
      if (category === '관광지') {
        return item.category === 'tourSpot';
      } else if (category === '카페') {
        return item.category === 'cafe';
      } else if (category === '식당') {
        return item.category === 'restaurant';
      } else {
        return item;
      }
    });
    return a;
  };

  useEffect(() => {
    const andeok = list?.filter((item) => {
      return item.areaid === 'Andeok';
    });
    const jocheon = list?.filter((item) => {
      return item.areaid === 'Jocheon';
    });
    const aewol = list?.filter((item) => {
      return item.areaid === 'Aewol';
    });
    if (area === '조천') {
      setDataList(filterTour(jocheon));
    } else if (area === '애월') {
      setDataList(filterTour(aewol));
    } else if (area === '안덕') {
      setDataList(filterTour(andeok));
    } else {
      setDataList(filterTour(list));
    }
  }, [area, category]);
  return [dataList];
};

api를 사용해보면서 문서를 읽고 공부하는 것에 대한 중요성을 알 수 있었다.

profile
https://github.com/Hediar?tab=repositories

1개의 댓글

comment-user-thumbnail
2023년 7월 18일

글이 잘 정리되어 있네요. 감사합니다.

답글 달기