지오펜스 설정(HTML)

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

이 항목에서는 앱에서 Geofence을 설정하는 단계를 안내합니다.

로드맵: 이 항목은 다음 항목과 연관되어 있습니다. 참고 항목:

소개

Geofence를 설정할 때 수행해야 할 몇 가지 단계가 있습니다. 관심 영역을 정의하는 것 외에도 적절한 위치 사용 권한이 있는지 확인해야 합니다. 마지막으로, 앱이 실행되는 동안 사용자가 그러한 사용 권한을 변경하는 경우에 대비하여 이벤트 처리기를 설정해야 합니다.

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

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

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

위치 접근 권한 값 사용

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

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

위치 사용 권한 확인

먼저 앱에 코드를 추가하여 초기화 중에 위치를 가져올 수 있습니다. Windows에서는 앱이 현재 위치를 가져오는 API를 처음 사용하는 경우 위치 사용 권한을 확인하는 메시지가 사용자에게 표시됩니다. 사용자가 앱에 사용 권한을 부여하지 않으면 사용자에게 경고가 표시됩니다. 위치 사용 권한 없이도 Geofence를 설정할 수 있지만, 사용 권한이 설정되기 전에는 알림을 받을 수 없습니다.

    function initialize() {

        promise = geolocator.getGeopositionAsync();
        promise.done(
            function (pos) {
                var coord = pos.coordinate;

            },
            function (err) {
            // handle situations where location permissions are not granted to your app
            }
        );

    }


위치 사용 권한 변경 수신 대기

이제, 사용자가 어떤 이유에서든 위치 사용 권한을 해제하는 경우에 대비하여 사용 권한 변경 이벤트를 등록해야 합니다. 먼저 초기화 메서드에 이벤트 처리기를 추가합니다.


var accessInfo = null;
accessInfo = DeviceAccessInformation.createFromDeviceClass(Enumeration.DeviceClass.location);
accessInfo.addEventListener("accesschanged", onAccessChanged);

그런 다음, 위치 사용 권한을 해제하면 지오펜싱이 더 이상 작동하지 않음을 사용자에게 알리도록 사용 권한 변경을 처리합니다.

function onAccessChanged(args) {
    var eventDescription = getTimeStampedMessage("Device Access Status");
    var item = null;

    if (DeviceAccessStatus.deniedByUser === args.status) {
        eventDescription += " (DeniedByUser)";

        WinJS.log && WinJS.log("Location has been disabled by the user. Enable access through the settings charm.", "sample", "status");
    } else if (DeviceAccessStatus.deniedBySystem === args.status) {
        eventDescription += " (DeniedBySystem)";

        WinJS.log && WinJS.log("Location has been disabled by the system. The administrator of the device must enable location access through the location control panel.", "sample", "status");
    } else if (DeviceAccessStatus.unspecified === args.status) {
        eventDescription += " (Unspecified)";

        WinJS.log && WinJS.log("Location has been disabled by unspecified source. The administrator of the device may need to enable location access through the location control panel, then enable access through the settings charm.", "sample", "status");
    } else if (DeviceAccessStatus.allowed === args.status) {
        eventDescription += " (Allowed)";

        // clear status
        WinJS.log && WinJS.log("", "sample", "status");
    } else {
        eventDescription += " (Unknown)";

        WinJS.log && WinJS.log("Unknown device access information status", "sample", "status");
    }

    addEventDescription(eventDescription);
}

참고  사용자가 LocationStatus 속성을 선택하여 설정에서 위치를 사용하지 않도록 설정했는지 확인할 수 있습니다. 값이 Disabled인 경우 위치가 사용되지 않습니다.

 

지오펜스 만들기

이제 지오펜스를 정의하고 설정할 준비가 되었습니다. 지오펜스에 대해 설정할 수 있는 몇 가지 값은 다음과 같습니다.

  • Id - 지오펜스를 식별합니다.
  • Geoshape - 순환 관심 영역을 정의합니다.
  • MonitoredStates - 정의된 지역으로 들어가거나, 정의된 지역을 떠나거나, 지오펜스를 제거는 경우 알림을 받을 지오펜스 이벤트를 나타냅니다.
  • SingleUse 플래그 - 지오펜스를 모니터링하는 모든 상태가 충족되었을 때 지오펜스를 제거합니다.
  • DwellTime - enter/exit 이벤트가 트리거되기까지 정의된 영역 내에 있거나 영역에서 벗어나는 시간을 나타냅니다.
  • StartTime - 지오펜스 모니터링을 시작해야 할 시기를 나타냅니다.
  • Duration - 지오펜스를 모니터링할 기간입니다.

function generateGeofence() {
    var geofence = null;

    try {
        var fenceKey = nameElement.value;

        var position = {
            latitude: decimalFormatter.parseDouble(latitude.value),
            longitude: decimalFormatter.parseDouble(longitude.value),
            altitude: 0
        };
        var radiusValue = decimalFormatter.parseDouble(radius.value);

        // the geofence is a circular region
        var geocircle = new Windows.Devices.Geolocation.Geocircle(position, radiusValue);

        var singleUse = false;

        if (geofenceSingleUse.checked) {
            singleUse = true;
        }

        // want to listen for enter geofence, exit geofence and remove geofence events
        var mask = 0;

        mask = mask | Windows.Devices.Geolocation.Geofencing.MonitoredGeofenceStates.entered;
        mask = mask | Windows.Devices.Geolocation.Geofencing.MonitoredGeofenceStates.exited;
        mask = mask | Windows.Devices.Geolocation.Geofencing.MonitoredGeofenceStates.removed;

        var dwellTimeSpan = new Number(parseTimeSpan(dwellTimeField, defaultDwellTimeSeconds));
        var durationTimeSpan = null;
        if (durationField.value.length) {
            durationTimeSpan = new Number(parseTimeSpan(durationField, 0));
        } else {
            durationTimeSpan = new Number(0); // duration needs to be set since start time is set below
        }
        var startDateTime = null;
        if (startTimeField.value.length) {
            startDateTime = new Date(startTimeField.value);
        } else {
            startDateTime = new Date(); // if you don't set start time in JavaScript the start time defaults to 1/1/1601
        }

        geofence = new Windows.Devices.Geolocation.Geofencing.Geofence(fenceKey, geocircle, mask, singleUse, dwellTimeSpan, startDateTime, durationTimeSpan);
    } catch (ex) {
        WinJS.log && WinJS.log(ex.toString(), "sample", "error");
    }

    return geofence;
}

관련 항목

로드맵

JavaScript로 작성한 앱용 로드맵

앱용 UX 디자인

작업

포그라운드에서 지오펜스 알림 처리

백그라운드에서 지오펜스 이벤트 수신 대기

백그라운드 작업에서 지오펜스 알림 처리

참조

Geoshape

Geofence

Geolocator

다른 리소스

Windows 10 지리적 위치 샘플

Windows 8.1 지리적 위치 샘플

지오펜싱에 대한 지침