FrontEnd, Kakao Map 현재 위치 나타내기(마커 표시), Vite + TypeScript(React)

Jihu Kim·2024년 12월 5일
0

FrontEnd

목록 보기
7/13
post-thumbnail

Geolocation API를 사용해서 사용자의 위치를 가져올 수 있다.

GeolocationPositionError {code: 1, message: 'User denied Geolocation'} 오류로 인해서 위치를 못가져오는 것 때문에 시간이 한참 걸렸다.

Geolocation API는 보안상의 이유로 HTTPS 환경에서만 동작한다.

개발 환경(http://localhost)에서는 동작하는데, 그런데도 동작하지 않는다면
chrome://settings/content/location에 접속해서 위치정보접근이 허용되었는지 확인해보자.

Geolocation API를 통해서 사용자 위치 가져오기

type LocationType = {
  lat: number;
  lng: number;
};

  const defaultLocation: LocationType = {
    lat: 33.450701,
    lng: 126.570667,
  };

  const [location, setLocation] = useState<LocationType>(defaultLocation);

  useEffect(() => {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        (position) => {
          setLocation({
            lat: position.coords.latitude,
            lng: position.coords.longitude,
          });
        },
        (error) => {
          console.error('Geolocation error:', error);
          // 사용자 거부 또는 오류 발생 시 디폴트 좌표 설정
          setLocation(defaultLocation);
        }
      );
    } else {
      console.error('Geolocation is not supported by this browser.');
      setLocation(defaultLocation);
    }
  }, []);
  1. 위치 좌표를 저장할 type을 지정한다.
  2. 기본 위치 좌표를 지정한다.
  3. useEffect를 통해서 페이지가 로드 될 때, geolocation을 통해서 사용자의 위치 좌표를 가져온다.
  4. 만약에 사용자의 위치 좌표를 가져오는 것에 실패하면 기본 위치 좌표로 설정한다.

현재 위치에 마커 표시하기

<MapMarker
          image={{
            src: myLocationMarker,
            size: { width: 30, height: 30 },
          }}
          position={location}
        />
  1. react-kakao-maps-sdk에서 MapMaker를 import하고 마커를 사용자의 위치에 표시한다.

전체 코드(KakaoMap.tsx)

import { useEffect, useState } from 'react';
import { Map, MapMarker } from 'react-kakao-maps-sdk';
// import clickLocationMarker from '../../assets/markers/clickLocation.png';
import myLocationMarker from '../../assets/markers/myLocation.png';
import * as styled from './KakaoMap.style';
import useKakaoLoader from './useKakaoLoader';

type LocationType = {
  lat: number;
  lng: number;
};

export default function KakaoMap() {
  useKakaoLoader();

  const defaultLocation: LocationType = {
    lat: 33.450701,
    lng: 126.570667,
  };

  const [location, setLocation] = useState<LocationType>(defaultLocation);

  useEffect(() => {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        (position) => {
          setLocation({
            lat: position.coords.latitude,
            lng: position.coords.longitude,
          });
        },
        (error) => {
          console.error('Geolocation error:', error);
          // 사용자 거부 또는 오류 발생 시 디폴트 좌표 설정
          setLocation(defaultLocation);
        }
      );
    } else {
      console.error('Geolocation is not supported by this browser.');
      setLocation(defaultLocation);
    }
  }, []);

  return (
    <styled.KakaoMapWrapper>
      <Map
        id="map"
        center={location} // 중심 좌표를 상태 값으로 설정
        style={{
          width: '100%', // 지도의 너비
          height: '100%', // 지도의 높이
        }}
        level={3} // 확대 레벨
      >
        <MapMarker
          image={{
            src: myLocationMarker,
            size: { width: 30, height: 30 },
          }}
          position={location}
        />
      </Map>
    </styled.KakaoMapWrapper>
  );
}

profile
Jihukimme

0개의 댓글