HTML5 API - Geolocation
HTML5 2012. 5. 11. 03:33
HTML5 API 중 지오로케이션(위치기반서비스)이라는 기능이 존재하며, 사용자 위치요청에 동의한 경우 브라우저가 위치 정보(위도, 경도 등..)를 반환합니다.
즉, 지오로케이션을 지원하는 브라우저가 실행 중인 스마트폰과 같은 여러 모바일 기기에서 위치 정보를 브라우저에게 전달하는 것입니다.
- 위치 정보를 알아오는 방법으로는 아래와 같이 총 4가지 방법이 존재합니다.
1. IP 주소 기반 데이터: 어디서나 사용 가능하나 정확도가 매우 낮다.
2. GPS 기반 지오로케이션 데이터: 매우 정확하다는 장점이 있지만, 위치 정보 판단을 위해 시간이 오래 소요되며, 그만큼 기기의 베터리를 소모한다.
3. Wi-Fi 기반 지오로케이션 데이터: 정확하나 무선 AP가 적은 지역에서는 정확도가 떨어진다.
4. 휴대전화 지오로케이션 데이터: 어느 정도 정확하나 기지국이 적은 지역에서는 정확도가 떨어진다.
지오로케이션 브라우저 지원 현황:
마지막으로 아래는 소스는 지오로케이션을 통해 받아온 위치정보를 구글맵과 연동하여, 현재 자신의 위치를 지도상에 표시하는 간단한 예제입니다.
-
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-
<html xmlns="http://www.w3.org/1999/xhtml">
-
<head>
-
<title>GeoLocation</title>
-
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
-
<meta charset="UTF-8">
-
<style type="text/css">
-
/*<[CDATA[*/
-
-
html, body, #map_canvas {
-
margin: 0;
-
padding: 0;
-
height: 100%;
-
}
-
/*]]>*/
-
</style>
-
</head>
-
<body>
-
<script type="text/javascript">
-
//<![CDATA[
-
-
bind(window, 'load', function () {
-
geolocationInit();
-
});
-
-
// 이벤트 할당
-
function bind(elem, type, handler, capture) {
-
type = typeof type === 'string' && type || '';
-
handler = handler || function () { ; };
-
-
if (elem.addEventListener) {
-
elem.addEventListener(type, handler, capture);
-
}
-
else if (elem.attachEvent) {
-
elem.attachEvent('on' + type, handler);
-
}
-
-
return elem;
-
};
-
-
-
-
function geolocationInit() {
-
-
if (navigator.geolocation) {
-
var geo = navigator.geolocation;
-
geo.getCurrentPosition(function (pos) {
-
// 위도
-
//alert(pos.coords.latitude);
-
// 경도
-
//alert(pos.coords.longitude);
-
// 정확도
-
//alert(pos.coords.accuracy);
-
// 마지막 업데이트 시간(초)
-
//alert(pos.timestamp);
-
-
// google map 연동
-
mapInit(pos.coords.latitude, pos.coords.longitude);
-
-
}, function (e) {
-
msg({
-
0: '위치 정보 검색에 문제가 있습니다.(msg:' + e.message + ')',
-
1: '현재 페이지에서 사용자가 위치 정보 검색을 거부했습니다.',
-
2: '브라우저가 위치정보를 검색하지 못했습니다.(msg:' + e.message + ')',
-
3: '브라우저의 위치 정보 검색 시간이 초과됐습니다.'
-
}[e.code]);
-
-
}, {
-
enableHeighAccuracy: false,
-
timeout: 10000,
-
maximumAge: 0
-
});
-
-
/*
-
-
var watchid = geo.watchCurrentPosition(updatecallback, errorcallback, opt): 위치정보검색을 반복한다.
-
geo.clearWatch(watchid): 위치정보검색 반복을 중지한다.
-
-
enableHeighAccuracy: HTML5 지오로케이션 서비스가 고도 정확도 감지모드를 사용할 수 있는지 여부를 브라우저에게 알려준다.
-
하지만 이 기능을 활성화하면 위치를 파악하느라 더 많은 시간과 전력이 소모된다.(기본값: false)
-
-
timeout: 위치 정보를 계산하는 시간을 의미하며, 정의된 시간이 넘어가면 에러를 발생시킨다.
-
-
maximumAge: 현 위치 정보에 대한 만료시간을 정의합니다.
-
-
-
-
-
*/
-
}
-
else {
-
alert('HTML 5 지오로케이션을 지원하지 않는 브라우저입니다.');
-
}
-
}
-
-
function msg(msg) {
-
alert(msg);
-
}
-
-
-
//]]>
-
</script>
-
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
-
<script type="text/javascript">
-
//<![CDATA[
-
-
function mapInit(latitude, longitude) {
-
var opt = {
-
zoom: 15,
-
center: new google.maps.LatLng(latitude, longitude),
-
mapTypeId: google.maps.MapTypeId.ROADMAP
-
};
-
-
var map = new google.maps.Map(document.getElementById('map_canvas'), opt);
-
};
-
//]]>
-
</script>
-
<div id="map_canvas"></div>
-
</body>
-
</html>
모바일 기기 실행결과:
크지 않은 오차범위로 현재 저의 위치정보를 정확하게 가져오는 것을 확인할 수 있습니다.
참고사이트:
레퍼런스:
http://www.w3schools.com/html5/html5_geolocation.asp
브라우저 지원현황