HTML5(HTML)를 사용하여 위치 검색

[ 이 문서는 Windows 런타임 앱을 작성하는 Windows에서 8.x 및 Windows Phone 8.x 개발자를 대상으로 합니다. Windows 10용으로 개발하는 경우에는 최신 설명서를 참조하세요.]

이 빠른 시작에서는 HTML5에서 제공하는 W3C Geolocation API를 사용하여 사용자의 지리적 위치를 검색하는 방법을 보여줍니다.

목표: HTML5를 사용하여 사용자의 지리적 위치를 검색하는 방법을 배웁니다.

사전 요구 사항

HTML과 JavaScript에 익숙해야 합니다.

완료 시간: 20 분.

지침

1. 위치를 사용하도록 설정했는지 확인

앱이 위치에 액세스하려면 먼저 장치에서 위치를 사용하도록 설정해야 합니다. 설정 앱에서 다음 위치 개인정보 설정이 켜져 있는지 확인합니다.

  • **이 장치의 위치...**가 켜짐 상태임(Windows 10 Mobile에는 해당되지 않음)
  • 위치 서비스 설정 위치켜짐 상태임
  • 사용자의 위치를 사용할 수 있는 앱 선택에서 앱이 on 상태임

2. Microsoft Visual Studio 열기

Visual Studio의 인스턴스를 엽니다.

3. 새 프로젝트 만들기

JavaScript/스토어 앱 프로젝트 유형에서 빈 앱을 선택하여 새 프로젝트를 만듭니다.

4. 위치 접근 권한 값 사용

Windows 및 Windows Phone 프로젝트에 대해 모두 솔루션 탐색기에서 package.appxmanifest를 두 번 클릭하고 기능 탭을 선택합니다. 그런 다음 접근 권한 값 목록에서 위치를 선택합니다. 그러면 Location 장치 접근 권한 값이 패키지 매니페스트 파일에 추가됩니다.

  <Capabilities>
    <!-- DeviceCapability elements must follow Capability elements (if present) -->
    <DeviceCapability Name="location"/>
  </Capabilities>

5. JavaScript 코드 바꾸기

공유 프로젝트에서 default.js(/js/default.js)를 엽니다. 파일의 코드를 다음과 같이 바꿉니다.

(function () {
    "use strict";

    var app = WinJS.Application;
    var activation = Windows.ApplicationModel.Activation;

    app.onactivated = function (args) {
        if (args.detail.kind === activation.ActivationKind.launch) {

            args.setPromise(WinJS.UI.processAll().
                done(function () {

                }));
        }
    };
(function () {
    "use strict";

    var app = WinJS.Application;
    var activation = Windows.ApplicationModel.Activation;

    app.onactivated = function (args) {
        if (args.detail.kind === activation.ActivationKind.launch) {

            args.setPromise(WinJS.UI.processAll().
                done(function () {

                    // Add an event handler to the button.
                    document.querySelector("#requestPosition").addEventListener("click",
                        requestPosition);

                }));
        }
    };

    var nav = null;

    function requestPosition() {
        if (nav == null) {
            nav = window.navigator;
        }

        var geoloc = nav.geolocation;
        if (geoloc != null) {
            geoloc.getCurrentPosition(successCallback, errorCallback);
        }

    }

    function successCallback(position) {
        document.getElementById("latitude").innerHTML =
            position.coords.latitude;
        document.getElementById("longitude").innerHTML =
            position.coords.longitude;

    }

    function errorCallback(error) {
        var strMessage = "";

        // Check for known errors
        switch (error.code) {
            case error.PERMISSION_DENIED:
                strMessage = "Access to your location is turned off. " +
                    "Change your settings to turn it back on.";
                break;
            case error.POSITION_UNAVAILABLE:
                strMessage = "Data from location services is " +
                    "currently unavailable.";
                break;
            case error.TIMEOUT:
                strMessage = "Location could not be determined " +
                    "within a specified timeout period.";
                break;
            default:
                break;
        }

        document.getElementById("status").innerHTML = strMessage;
    }

    app.start();
})();

6. 앱에 대한 HTML 추가

Windows 및 Windows Phone 프로젝트에 대한 default.html 파일을 열고 다음 HTML을 파일의 BODY 태그 내부에 복사합니다.

    <label for="latitude">Latitude: </label> <div id="latitude"></div><br />
    <label for="longitude">Longitude: </label> <div id="longitude"> </div><br />
    <div id="status"> </div><br />

    <button id="requestPosition">Get Latitude and Longitude</button><br />

7. 앱 빌드

빌드 > 솔루션 빌드를 클릭하여 프로젝트를 빌드합니다.

8. 앱 테스트

  1. 디버그 메뉴에서 디버깅 시작을 클릭하여 솔루션을 테스트합니다.
  2. 샘플을 처음 실행하면 앱에서 위치를 사용할 수 있는지를 묻는 메시지가 표시됩니다. 허용 옵션을 선택합니다.
  3. 위치 가져오기 단추를 클릭하여 현재 위치를 가져옵니다.

요약

이 빠른 시작에서는 HTML5를 사용하여 사용자의 현재 위치를 검색하는 간단한 앱을 만들었습니다. 자세한 내용은 위치 인식 웹 페이지 빌드 항목을 참조하세요.

관련 항목

Windows 10 지리적 위치 샘플

Windows 8.1 지리적 위치 샘플

Bing 지도 SDK 샘플