더 나은 프로그래머가 되자

geolocation을 이용한 현재 좌표 확인 및 좌표로 현재 주소 위치 나타내기 본문

API/다음

geolocation을 이용한 현재 좌표 확인 및 좌표로 현재 주소 위치 나타내기

greathuman 2015. 5. 27. 11:38

html5의 w3g표준 API인 geolocation를 이용해서 현재위치 정보를 알아낼 수 있다.

geolocation는 GPS뿐만 아니라 IP주소나 WIFI정보로 현재위치 정보를 습득해서 알려주게되고
이는 각 브라우저에서 자동으로 판단해서 처리하게되므로 어떤 정보를 통해 좌표를 습득했는지

개발자는 알 수 없다.

 

 

<SCRIPT src="//code.jquery.com/jquery-1.11.3.min.js"></SCRIPT>
<SCRIPT type=text/javascript src="//apis.daum.net/maps/maps3.js?apikey=d7d8183995cac01712f6ea9af98b9587&libraries=services"></SCRIPT>

function now_location(){
	if(navigator.geolocation){
		navigator.geolocation.getCurrentPosition(
			// successCallback
			function(position) {
				var lat = position.coords.latitude;  // 위도
				var lon = position.coords.longitude; // 경도
				//다음지도 API 좌표로 주소값 구하기 
				var geocoder = new daum.maps.services.Geocoder();
				var coord = new daum.maps.LatLng(lat, lon);
				var callback = function(status, result) {
					if (status === daum.maps.services.Status.OK) {
						var area_txt = result[0].fullName;
						var area_arr = area_txt.split(" "); 
						var area_dong = area_arr[2] //동까지만 표시
						$("#str_area").val(area_txt);
					}
				};

				geocoder.coord2addr(coord, callback);
				//다음지도 API 끝
			}, 
			// errorCallback
			function(error)
			{
				switch(error.code) 
				{    
					case error.TIMEOUT:
						alert ('시간 초과');
						break;
					case error.POSITION_UNAVAILABLE:
						alert ('위치를 사용할 수 없음 (이 오류는 위치 정보 공급자가 응답)');    
						break;
					case error.PERMISSION_DENIED: 
						alert ('위치정보 서비스가 꺼져있거나 권한이 없습니다.');
						break;
					case error.UNKNOWN_ERROR:    
						alert ('알 수 없는 오류');
						break;
					default : 
						alert ( errro.code);
				}
			});
	}
	else{
		alert("이 브라우저는 geolcation API를 지원하지 않습니다");
	}
}
<INPUT id=str_area readOnly> <INPUT onclick=now_location(); type=button value="현재위치 확인">

 

 

 

geolocation API는 디바이스의 위치서비스 기능이 켜져있어야하며 위치서비스가 꺼져있을경우 퍼미션디나이 에러케이스로 넘어가게된다.

 

 

 

 

위 스크립트는 다음지도 API와 연계해서 현재 위치 좌표를 geolocation로 얻어내고 그 좌표값을 다음 API 메소드인 coord2addr를 이용해서 주소값

 

으로 변환해주는 스크립트이다.

 

결과는 아래와 같다.

 

 

 

'API > 다음' 카테고리의 다른 글

다음 지도 약도 만들기  (0) 2015.09.18
[지도 API] 주소 검색으로 지도에 위치 표시하기  (0) 2015.05.22
Comments