Share via


위치 업데이트에 응답(HTML)

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

이 항목에서는 사용자 위치의 변경에 응답하는 방법에 대해 설명합니다.

알아야 할 사항

기술

  • Windows Runtime

사전 요구 사항

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

지침

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

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

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

단계 2: Microsoft Visual Studio 열기

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

단계 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 () {

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

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

                }));
        }
    };

    var loc = null;

    function trackloc() {
        if (loc == null) {
            loc = new Windows.Devices.Geolocation.Geolocator();
        }
        if (loc != null) {
            loc.addEventListener("positionchanged", onPositionChanged);
            loc.addEventListener("statuschanged", onStatusChanged);
            // display initial status, in case location is turned off.
            document.getElementById('geolocatorStatus').innerHTML =
                getStatusString(loc.locationStatus);
        }
    }

    function stoptracking() {
        if (loc != null) {
            loc.removeEventListener("positionchanged", onPositionChanged);
        }
    }

    function onPositionChanged(args) {
        var pos = args.position;
        document.getElementById('latitude').innerHTML =
            pos.coordinate.point.position.latitude;
        document.getElementById('longitude').innerHTML =
            pos.coordinate.point.position.longitude;
        document.getElementById('accuracy').innerHTML =
            pos.coordinate.accuracy;
        document.getElementById('geolocatorStatus').innerHTML =
                getStatusString(loc.locationStatus);
    }

    // Handle change in status to display an appropriate message.        
    function onStatusChanged(args) {
        var newStatus = args.status;
        document.getElementById('geolocatorStatus').innerHTML =
            getStatusString(newStatus);
    }

    function getStatusString(locStatus) {
        switch (locStatus) {
            case Windows.Devices.Geolocation.PositionStatus.ready:
                // Location data is available
                return "Location is available.";
                break;
            case Windows.Devices.Geolocation.PositionStatus.initializing:
                // This status indicates that a GPS is still acquiring a fix
                return "A GPS device is still initializing.";
                break;
            case Windows.Devices.Geolocation.PositionStatus.noData:
                // No location data is currently available
                return "Data from location services is currently unavailable.";
                break;
            case Windows.Devices.Geolocation.PositionStatus.disabled:
                // The app doesn't have permission to access location,
                // either because location has been turned off.
                return "Your location is currently turned off. " +
                    "Change your settings through the Settings charm " +
                    " to turn it back on.";
                break;
            case Windows.Devices.Geolocation.PositionStatus.notInitialized:
                // This status indicates that the app has not yet requested
                // location data by calling GetGeolocationAsync() or
                // registering an event handler for the positionChanged event.
                return "Location status is not initialized because " +
                    "the app has not requested location data.";
            case Windows.Devices.Geolocation.PositionStatus.notAvailable:
                // Location is not available on this version of Windows
                return "You do not have the required location services " +
                    "present on your system.";
                break;
            default:
                return "Unknown status.";
        }
    }

    app.start();
})();

단계 6: 앱에 대한 HTML 추가

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

    <p>Geolocation Event Sample</p><br />
    <span id="status"></span><br />
    <button id="startTracking">Track Location</button><br />
    <br />
    <button id="stopTracking">Stop Tracking</button><br />
    Latitude: <span id="latitude">Waiting for update...</span><br />
    Longitude:  <span id="longitude">Waiting for update...</span><br />
    Accuracy (in meters): <span id="accuracy">Waiting for update...</span><br />
    Location Status: <span id="geolocatorStatus"></span><br />

단계 7: 앱 빌드

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

단계 8: 앱 테스트

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

설명

위치 서비스는 많은 다른 소스를 사용하여 위치를 결정합니다. GPS, 셀 타워 및 Wi-Fi를 사용할 수 없는 경우 대신 IP 주소를 사용합니다. 이 경우 IP 주소 데이터는 자주 업데이트되지 않으므로 위치 업데이트 이벤트를 받지 못할 수 있습니다.

위치 데이터를 한 번만 가져와야 하는 경우, 업데이트를 구독하는 GetGeopositionAsync빠른 시작에서 설명된 바와 같이 메서드를 사용합니다. 사용자 위치 검색.

관련 항목

Windows 10 지리적 위치 샘플

Windows 8.1 지리적 위치 샘플

Windows.Devices.Geolocation