IT's 우

[HTML5, 3주차-2] Geo Location, 카카오맵 API, File API 본문

카카오 클라우드 스쿨 2기/frontend

[HTML5, 3주차-2] Geo Location, 카카오맵 API, File API

디우 2022. 11. 15. 18:38
728x90

1. Geo Location

1) 개요

  • 디바이스의 물리적 위치 정보를 파악하기 위한 Javascript API
  • 위치 정보

2) 위치 정보 사용 가능 여부 확인

  • navigator.geolocation의 값 확인

3) 위치 정보를 가져와서 한 번만 사용하기

  • navigator.geolocation.getCurrentPosition(위치 정보를 가져오는 데 성공했을 때 호출되는 함수, 위치 정보를 가져오는 데 실패했을 때 호출되는 함수, 옵션)
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>GeoLoation</title>
    <script>
        //navigator.geolocation.getCurrentPosition
        //(위치 정보를 가져오는데 성공했을 때 호출되는 함수, 
        //위치 정보를 가져오는데 실패했을 때 호출되는 함수, 옵션)
        navigator.geolocation.getCurrentPosition((position)=>{
            alert("위도: "+position.coords.latitude+", 경도: "+ position.coords.longitude)
        },(error)=>{
            alert(error.code);
        },{
            maximumAge:5000,
            enableHighAccuracy: true
        })
    </script>
</head>
<body>
    
</body>
</html>

 

4) 위치 정보를 계속 가져와서 사용하기

  • let 변수 = navaigetor.geolocation.watchPosition(위치 정보를 가져오는데 성공했을 때 호출되는 함수, 위치 정보를 가져오는데 실패했을 때 호출되는 함수, 옵션)로 위치 정보를 계속해서 파악하고 clearWatch(변수)를 호출하면 더 이상 위치 정보를 가져오지 않습니다.

5) 옵션

6) 웹화면에 현재 위치에 해당하는 카카오 맵을 이용

 

https://developers.kakao.com/

 

Kakao Developers

카카오 API를 활용하여 다양한 어플리케이션을 개발해보세요. 카카오 로그인, 메시지 보내기, 친구 API, 인공지능 API 등을 제공합니다.

developers.kakao.com

  • 애플리케이션 생성하고 javascript 키 복사: 
    키는 바로 사용이 불가능- 플랫폼을 등록해야 한다.
    네이티브 앱은 앱의 패키지 이름을 등록해야 웹의 경우는 도메인을 등록해야 합니다.
    연습할 때는 웹으 경우는 http://localhost:포트번호 형태로 등록하고 실제 서비스에 사용을 할 때는 localhost:포트번호 대신에 등록한 도메인이나 실 사용이 가능한 공인 IP 형태로 변경을 해야 합니다.

 

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <title>Kakao 지도 시작하기</title>
</head>

<body>
    <div id="map" style="width:500px;height:400px;"></div>
    <script type="text/javascript"
        src="//dapi.kakao.com/v2/maps/sdk.js?appkey=f2e17aeed3c1967e0b52038107786813"></script>
    <script>
        navigator.geolocation.getCurrentPosition((position) => {
            //https://apis.map.kakao.com/web/guide/
            var container = document.getElementById('map');
            var options = {
                center: new kakao.maps.LatLng(position.coords.latitude, position.coords.longitude),
                level: 3
            };

            var map = new kakao.maps.Map(container, options);

            // 마커가 표시될 위치입니다 
            var markerPosition = new kakao.maps.LatLng(position.coords.latitude, position.coords.longitude);

            // 마커를 생성합니다
            var marker = new kakao.maps.Marker({
                position: markerPosition
            });

            // 마커가 지도 위에 표시되도록 설정합니다
            marker.setMap(map);

            // 아래 코드는 지도 위의 마커를 제거하는 코드입니다
            // marker.setMap(null);    
        }, (error) => {
            alert(error.code);
        }, {
            maximumAge: 5000,
            enableHighAccuracy: true
        })

    </script>
</body>

</html>

 

 


2. File API

  • File을 읽고 쓰기 위한 API
  • input 타입의 file에 multiple 속성이 추가돼서 이 속성의 값을 설정하면 여러 개의 파일을 선택하는 것이 가능
  • 텍스트 파일을 읽을 때는 인코딩 설정에 주의해야 합니다.
  • 일반 파일을 읽을 때는 FileReader 객체를 생성한 후 reader.readAdDataURL(파일 객체)를 호출하고 load 이벤트와 error 이벤트를 처리합니다.
    load는 전부 읽었을 때 FileReader 객체의 result에 읽은 내용을 저장하고 error 이벤트는 읽기에 실패했을 때 실패한 이유를 저장하고 있는 객체를 넘겨줍니다.

  • 이미지 미리 보기
<!DOCTYPE html>
<html lang="ko">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>이미지 미리보기</title>
</head>

<body>
    <!-- 이미지 파일만 선택할 수 있는 file 객체-->
    <input type="file" id="imginput" accept="image/*" />
    <!--  <input type="file" accept=".png,.jpg,.jpge,.gif" /> -->
    <!-- 이미지 미리보기 영역 -->
    <img id="display" width="250" height="250" />

    <script>
        // 필요한 DOM 객체 찾아오기
        let imginput = document.getElementById("imginput");
        let display = document.getElementById("display");

        // imginput의 선택이 변경되면 
        imginput.addEventListener("change", (e) => {
            // 선택한 파일의 내용을 읽기
            let reader = new FileReader();
            // 파일이 선택되었는지 확인
            // javascript는 0이 아닌 숫자나
            // null이나 undefined가 아니면 true로 간주- truthy
            if(!(imginput.files &&imginput.files[0])){
                alert("선택된 파일이 없음");
                display.src=null;
                return;
            }
            reader.readAsDataURL(imginput.files[0]);
            // 파일의 내용을 전부 읽으면
            reader.addEventListener("load", () => {
                // 읽은 내용을 이미지의 소스로 사용
                display.src = reader.result;
            })
        });
    </script>
</body>

</html>
728x90
반응형