Geolocation API는 브라우저가 사용자의 지리적 위치를 찾아내고 그 정보를 애플리케이션에서 이용할 수 있도록 하는 기능이다. 사용자의 위치 정보를 이용하기 위해서는 먼저 승인 절차를 거쳐야 하며, 승인이 완료 된 상태라면 사용자 컨텐츠가 생성될 때 지오-태깅(geo-tagging)기능을 제공할 수 있고 근처에서 촬영된 사진 등에 대한 정보를 유기적으로 연결시켜 서비스할 수 있다.
그리고 사용자의 위치가 변경 될 때 마다 콜백 메서드로 전달되어 항상 최신의 위치 정보를 유지하는 것이 가능하다.
이러한 지리 정보는 기본적으로GPS 장치로 부터 얻어지는 것이 가장 정확하지만 그외 지리 정보를 얻을 수 있는 수단들을 단계적으로 이용하여 최소한 수도 또는 국가 단위의 지리 정보를 취득할 수 있다
[예제] 이동 거리 측정기
※ 출처: http://html5.firejune.com/demo/geolocation.html
<!DOCTYPE html> <html> <head> <title>Geolocation Demo : http://html5.firejune.com/demo/geolocation.htmla</title> <meta http-equiv="Content-Type" content="text/html; charset=euc-kr"> </head> <body> <h1>Geolocation Demo</h1> <div id="tripmeter"> <p> 시작 위치 (위도, 경도):<br/> <span id="startLat"></span>°, <span id="startLon"></span>° </p> <p> 현재 위치 (위도, 경도):<br/> <span id="currentLat"></span>°, <span id="currentLon"></span>° </p> <p> 시작 위치로 부터의 거리:<br/> <span id="distance">0</span> km </p> </div> <script> window.onload = function() {
var startPos;
if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { startPos = position; document.getElementById("startLat").innerHTML = startPos.coords.latitude; document.getElementById("startLon").innerHTML = startPos.coords.longitude; }, function(error) { alert("Error occurred. Error code: "+error.code); // error.code는 다음을 의미함: // 0: 알 수 없는 오류 // 1: 권한 거부 // 2: 위치를 사용할 수 없음 (이 오류는 위치 정보 공급자가 응답) // 3: 시간 초과 });
navigator.geolocation.watchPosition(function(position) { document.getElementById("currentLat").innerHTML = position.coords.latitude; document.getElementById("currentLon").innerHTML = position.coords.longitude; document.getElementById("distance").innerHTML = calculateDistance(startPos.coords.latitude, startPos.coords.longitude, position.coords.latitude, position.coords.longitude); }); } };
// Reused code - copyright Moveable Type Scripts - retrieved May 4, 2010. // http://www.movable-type.co.uk/scripts/latlong.html // Under Creative Commons License http://creativecommons.org/licenses/by/3.0/ function calculateDistance(lat1, lon1, lat2, lon2) { var R = 6371; // km var dLat = (lat2-lat1).toRad(); var dLon = (lon2-lon1).toRad(); var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) * Math.sin(dLon/2) * Math.sin(dLon/2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); var d = R * c; return d; } Number.prototype.toRad = function() { return this * Math.PI / 180; } </script> </body> </html> |