HTML5를 사용하여 위치 업데이트에 응답(HTML)
[ 이 문서는 Windows 런타임 앱을 작성하는 Windows에서 8.x 및 Windows Phone 8.x 개발자를 대상으로 합니다. Windows 10용으로 개발하는 경우에는 최신 설명서를 참조하세요.]
이 항목에서는 HTML5의 W3C Geolocation API를 사용하여 사용자의 지리적 위치 변경에 응답하는 방법을 보여줍니다.
사전 요구 사항
HTML과 JavaScript에 익숙해야 합니다.
지침
단계 1: Microsoft Visual Studio 열기
Visual Studio의 인스턴스를 엽니다.
단계 2: 위치를 사용하도록 설정했는지 확인
앱이 위치에 액세스하려면 먼저 장치에서 위치를 사용하도록 설정해야 합니다. 설정 앱에서 다음 위치 개인정보 설정이 켜져 있는지 확인합니다.
- **이 장치의 위치...**가 켜짐 상태임(Windows 10 Mobile에는 해당되지 않음)
- 위치 서비스 설정 위치가 켜짐 상태임
- 사용자의 위치를 사용할 수 있는 앱 선택에서 앱이 on 상태임
단계 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("#watchLoc").addEventListener("click",
watchloc);
// Add an event handler to the button.
document.querySelector("#stopWatching").addEventListener("click",
stopwatching);
}));
}
};
var loc = null;
var watchId;
function watchloc() {
if (loc == null) {
loc = window.navigator.geolocation;
}
if (loc != null) {
watchId = loc.watchPosition(successCallback);
}
}
function stopwatching() {
loc.clearWatch(watchId);
}
function successCallback(pos) {
document.getElementById('latitude').innerHTML = pos.coords.latitude;
document.getElementById('longitude').innerHTML = pos.coords.longitude;
document.getElementById('accuracy').innerHTML = pos.coords.accuracy;
}
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 태그 내부에 복사합니다.
Geolocation Event Sample<br />
<br />
<button id="watchLoc">Watch Location</button><br />
<button id="stopWatching">Stop Watching</button><br />
Latitude: <span id="latitude">Waiting for update...</span><br />
Longitude: <span id="longitude">Waiting for update...</span><br />
Accuracy: <span id="accuracy">Waiting for update...</span><br />
<span id="status"> </span><br />
단계 7: 앱 빌드
빌드 > 솔루션 빌드를 클릭하여 프로젝트를 빌드합니다.
단계 8: 앱 테스트
- 디버그 메뉴에서 디버깅 시작을 클릭하여 솔루션을 테스트합니다.
- 샘플을 처음 실행하면 앱에서 위치를 사용할 수 있는지를 묻는 메시지가 표시됩니다. 허용 옵션을 선택합니다.
- 위치 가져오기 단추를 클릭하여 현재 위치를 가져옵니다.
설명
위치 서비스는 많은 다른 소스를 사용하여 위치를 결정합니다. GPS, 셀 타워 및 Wi-Fi를 사용할 수 없는 경우 대신 IP 주소를 사용합니다. 이 경우 IP 주소 데이터는 자주 업데이트되지 않으므로 위치 업데이트 이벤트를 받지 못할 수 있습니다.