HTML5 API - Geolocation


HTML5 API 중 지오로케이션(위치기반서비스)이라는 기능이 존재하며, 사용자 위치요청에 동의한 경우 브라우저가 위치 정보(위도, 경도 등..)를 반환합니다.


즉, 지오로케이션을 지원하는 브라우저가 실행 중인 스마트폰과 같은 여러 모바일 기기에서 위치 정보를 브라우저에게 전달하는 것입니다.



- 위치 정보를 알아오는 방법으로는 아래와 같이 총 4가지 방법이 존재합니다.


1. IP 주소 기반 데이터: 어디서나 사용 가능하나 정확도가 매우 낮다.


2. GPS 기반 지오로케이션 데이터: 매우 정확하다는 장점이 있지만, 위치 정보 판단을 위해 시간이 오래 소요되며, 그만큼 기기의 베터리를 소모한다.


3. Wi-Fi 기반 지오로케이션 데이터: 정확하나 무선 AP가 적은 지역에서는 정확도가 떨어진다.


4. 휴대전화 지오로케이션 데이터: 어느 정도 정확하나 기지국이 적은 지역에서는 정확도가 떨어진다.





지오로케이션 브라우저 지원 현황:






마지막으로 아래는 소스는 지오로케이션을 통해 받아온 위치정보를 구글맵과 연동하여, 현재 자신의 위치를 지도상에 표시하는 간단한 예제입니다.


  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4.     <title>GeoLocation</title>
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
  6.     <meta charset="UTF-8">
  7.     <style type="text/css">
  8.     /*<[CDATA[*/
  9.  
  10.         html, body, #map_canvas {
  11.             margin: 0;
  12.             padding: 0;
  13.             height: 100%;
  14.         }
  15.     /*]]>*/
  16.     </style>
  17. </head>
  18. <body>
  19. <script type="text/javascript">
  20. //<![CDATA[
  21.  
  22.     bind(window, 'load', function () {
  23.         geolocationInit();
  24.     });
  25.  
  26.     // 이벤트 할당
  27.     function bind(elem, type, handler, capture) {
  28.         type = typeof type === 'string' && type || '';
  29.         handler = handler || function () { ; };
  30.  
  31.         if (elem.addEventListener) {
  32.             elem.addEventListener(type, handler, capture);
  33.         }
  34.         else if (elem.attachEvent) {
  35.             elem.attachEvent('on' + type, handler);
  36.         }
  37.  
  38.         return elem;
  39.     };
  40.  
  41.  
  42.  
  43.     function geolocationInit() {
  44.  
  45.         if (navigator.geolocation) {
  46.             var geo = navigator.geolocation;
  47.             geo.getCurrentPosition(function (pos) {
  48.                 // 위도
  49.                 //alert(pos.coords.latitude);
  50.                 // 경도
  51.                 //alert(pos.coords.longitude);
  52.                 // 정확도
  53.                 //alert(pos.coords.accuracy);
  54.                 // 마지막 업데이트 시간(초)
  55.                 //alert(pos.timestamp);
  56.  
  57.                 // google map 연동
  58.                 mapInit(pos.coords.latitude, pos.coords.longitude);
  59.  
  60.             }, function (e) {
  61.                 msg({
  62.                     0: '위치 정보 검색에 문제가 있습니다.(msg:' + e.message + ')',
  63.                     1: '현재 페이지에서 사용자가 위치 정보 검색을 거부했습니다.',
  64.                     2: '브라우저가 위치정보를 검색하지 못했습니다.(msg:' + e.message + ')',
  65.                     3: '브라우저의 위치 정보 검색 시간이 초과됐습니다.'
  66.                 }[e.code]);
  67.  
  68.             }, {
  69.                 enableHeighAccuracy: false,
  70.                 timeout: 10000,
  71.                 maximumAge: 0
  72.             });
  73.  
  74.             /*
  75.  
  76.             var watchid = geo.watchCurrentPosition(updatecallback, errorcallback, opt): 위치정보검색을 반복한다.
  77.             geo.clearWatch(watchid): 위치정보검색 반복을 중지한다.
  78.  
  79.             enableHeighAccuracy: HTML5 지오로케이션 서비스가 고도 정확도 감지모드를 사용할 수 있는지 여부를 브라우저에게 알려준다.
  80.             하지만 이 기능을 활성화하면 위치를 파악하느라 더 많은 시간과 전력이 소모된다.(기본값: false)
  81.  
  82.             timeout: 위치 정보를 계산하는 시간을 의미하며, 정의된 시간이 넘어가면 에러를 발생시킨다.
  83.  
  84.             maximumAge: 현 위치 정보에 대한 만료시간을 정의합니다.
  85.  
  86.  
  87.  
  88.  
  89.             */
  90.         }
  91.         else {
  92.             alert('HTML 5 지오로케이션을 지원하지 않는 브라우저입니다.');
  93.         }
  94.     }
  95.  
  96.     function msg(msg) {
  97.         alert(msg);
  98.     }
  99.  
  100.  
  101. //]]>
  102. </script>
  103. <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
  104. <script type="text/javascript">
  105. //<![CDATA[
  106.  
  107.     function mapInit(latitude, longitude) {
  108.         var opt = {
  109.             zoom: 15,
  110.             center: new google.maps.LatLng(latitude, longitude),
  111.             mapTypeId: google.maps.MapTypeId.ROADMAP
  112.         };
  113.  
  114.         var map = new google.maps.Map(document.getElementById('map_canvas'), opt);
  115.     };
  116. //]]>
  117. </script>
  118. <div id="map_canvas"></div>
  119. </body>
  120. </html>


모바일 기기 실행결과:






크지 않은 오차범위로 현재 저의 위치정보를 정확하게 가져오는 것을 확인할 수 있습니다.



참고사이트:


레퍼런스: 

http://www.w3schools.com/html5/html5_geolocation.asp


브라우저 지원현황

http://caniuse.com/