React 카카오 map api 가져오기

hwakyoung·2024년 2월 19일
0
post-thumbnail

👍🏻 카카오 map api를 가져오기

https://apis.map.kakao.com/web/
이 사이트를 이용해서 카카오 map api를 만들어보자
좌즉에 있는 열쇠모양을 눌러서 키를 발급받아보자.



  • 키 모양을 누르게 되면 이렇게 로그인 창이 뜨게 되는데 자신의 카카오톡 아이디와 비밀번호를 입력하면 된다.


그러면 이러한 창이 뜨게 된다.

  • 여기서 애플리케이션 추가를 눌러서 추가해 주면 된다.
  • 그 다음에 자바스크립트 코드를 사용하면 된다.


  • 플렛폼에 들어와서 자신이 개발하고 있는 것에 대해 플렛폼을 선택하고
    등록을 눌러서 자신이 사용할 주소를 넣어주면 된다.

  • 나는 아직 개발중이라 localhost로 넣었지만 배포를 했다면 배포한 주소를 넣어주면 된다. 꼭 자신이 사용할 주소를 넣어주셉...
    주인장은 그거땜시 2시간을 버렸다는....


🚩 React 지도 띄우기

먼저 지도를 띄우기 위해서 create-react-app으로 나는 시작을 하였고, public에 있는 index.html파일에 가서 밑에 있는 스크립트 코드를
넣어주면 된다.

<script type="text/javascript" src="//dapi.kakao.com/v2/maps/sdk.js?appkey=	자신이 부여받은 js키"></script>

전체 코드로 보면 이런느낌 head밑에 아무곳이나 넣어도 상관없다.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <title>React App</title>
    <script type="text/javascript" src="//dapi.kakao.com/v2/maps/sdk.js?appkey=	아까 부여받은 js키"></script>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>

🚩 초반 지도 띄우기

그런후에 jsx 파일을 만들어서 해당 코드를 작성해주면 된다.

/*global kakao*/
import { useEffect } from "react";
import '../Location/location.css'

const Location = () => {

    useEffect(() => {
        var container = document.getElementById('map');
        var options = {
          //지도의 중간 위치를 가져옴
            center: new kakao.maps.LatLng(37.365264512305174, 127.10676860117488),
          	//우리에게 보이는 지도 크기 => 숫자가 클 수록 멀리서 보는 st
            level: 3
        };

        var map = new kakao.maps.Map(container, options);
        var markerPosition = new kakao.maps.LatLng(37.365264512305174, 127.10676860117488);
        var marker = new kakao.maps.Marker({
            position: markerPosition
        });
        marker.setMap(map);

    }, [])


    return (
        <div>
        	//지도 크기 설정
            <div className="map" id="map" style={{ width: "328px", height: "536px"}}></div>
        </div>
    )
}

export default Location;

그럼 이런식으로 자신의 현재 위치가 출력되게 된다.


🚩 내 현재 위치의 경도와 위도를 가져와 보자

아래 사이트를 이용하면 지도를 다양하게 바꿀 수 있도록 도와준다.

https://apis.map.kakao.com/web/sample/

위에 코드에서 살짝 쿵 추가를 하면 된다.
내 위치 가져오기라는 버튼을 눌렀을 때 현재 위치의 위도와 경도가 보이게 만들었다.

  • 또한 중간중간에 내 위치를 가리키는 핀이 움직일 수 있게 구현,
  • 스크롤로 지도의 크기를 움직일 수 있게 구현하였다.
    • (사실 gpt를 안썻다면 거짓말.. 조금의 도움을 받았다.)
import { useEffect, useState } from "react";
import '../Location/location.css';

const Location = () => {
    const [state, setState] = useState({
        center: { lat: 37.365264512305174, lng: 127.10676860117488 },
        isPanto: false,
        userLocation: null // 추가: 사용자의 현재 위치를 저장할 상태 추가
    });

    useEffect(() => {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(
                (position) => {
                    const userLat = position.coords.latitude;
                    const userLng = position.coords.longitude;
                    initializeMap(userLat, userLng);
                },
                (error) => {
                    console.error("사용자 위치를 가져오는 중 오류 발생:", error.message);
                    initializeMap(state.center.lat, state.center.lng);
                }
            );
        } else {
            console.error("이 브라우저에서는 지오로케이션을 지원하지 않습니다.");
            initializeMap(state.center.lat, state.center.lng);
        }
    }, [state.center.lat, state.center.lng]);

    const initializeMap = (initialLat, initialLng) => {
        const container = document.getElementById('map');
        const options = {
            center: new window.kakao.maps.LatLng(initialLat, initialLng), // Use window.kakao.maps.LatLng
            level: 3
        };

        const map = new window.kakao.maps.Map(container, options); // Use window.kakao.maps.Map
        const markerPosition = new window.kakao.maps.LatLng(initialLat, initialLng); // Use window.kakao.maps.LatLng
        const marker = new window.kakao.maps.Marker({
            position: markerPosition,
            draggable: true
        });
        marker.setMap(map);

        // 클릭 이벤트 리스너 추가
        window.kakao.maps.event.addListener(map, 'click', function (mouseEvent) {
            // 클릭한 좌표로 마커의 위치 업데이트
            marker.setPosition(mouseEvent.latLng);
        });

        // 드래그 이벤트 리스너 추가
        window.kakao.maps.event.addListener(marker, 'dragend', function () {
            // 마커의 새로운 위치로 지도 중심 이동
            map.setCenter(marker.getPosition());
        });
    };

    // 추가: 사용자의 현재 위치를 가져오는 함수
    const getUserLocation = () => {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(
                (position) => {
                    const userLat = position.coords.latitude;
                    const userLng = position.coords.longitude;
                    setState(prevState => ({
                        ...prevState,
                        userLocation: { lat: userLat, lng: userLng } // 사용자 위치 업데이트
                    }));
                },
                (error) => {
                    console.error("사용자 위치를 가져오는 중 오류 발생:", error.message);
                }
            );
        } else {
            console.error("이 브라우저에서는 지오로케이션을 지원하지 않습니다.");
        }
    };

    return (
        <div className="location">
            <p>회원가입</p><hr />
            <div className="map" id="map" style={{ width: "328px", height: "536px" }}></div>
            <button onClick={getUserLocation}>내 위치 가져오기</button> {/* 수정: 버튼 클릭 시 getUserLocation 함수 호출 */}
            {/* 추가: 사용자 위치가 있는 경우 화면에 표시 */}
            {state.userLocation && (
                <p>현재 위치: 위도 {state.userLocation.lat}, 경도 {state.userLocation.lng}</p>
            )}
        </div>
    );
}

export default Location;

🚩 경도 위도를 주소로 바꾸기

해당 코드를 위에다가 추가해주면 내 위치가 주소로 뜨게 된다.

    const getAddressFromCoordinates = (lat, lng) => {
        const apiUrl = `https://nominatim.openstreetmap.org/reverse?format=json&lat=${lat}&lon=${lng}`;

        fetch(apiUrl)
            .then(response => response.json())
            .then(data => {
                if (data.display_name) {
                    const address = data.display_name;
                    setState(prevState => ({
                        ...prevState,
                        userLocation: { lat, lng, address }
                    }));
                } else {
                    console.error("주소를 찾을 수 없습니다.");
                }
            })
            .catch(error => {
                console.error("주소를 가져오는 중 오류 발생:", error.message);
            });
    };

저런식으로 주소가 뜨게 된다.


하면서 진짜 주소 불러오는게 너무 어려웠음...ㅠㅠㅠ 구글에서 지원하는 api를 쓰려고 했는데 카드 등록도 해야하고 돈도 내는게 두려워서 무료를 찾아보다가 발견한 api를 사용했다.
https://nominatim.openstreetmap.org 여기서 바꿔준다고 하늬ㅠㅠ 정보가 많이 없어서 힘들었지만 그래도 해냈다 ..ㅜㅜ 지도 api불러오는 모든분들 존경합니다ㅠㅠ.. 열심히 해봅시다~!

profile
fire-irror

0개의 댓글

관련 채용 정보