현재 위치 구하기 (PHP)

geolocation 함수를 통해 위치를 구하고, 만약 관련 권한 및 지원하지 않는 브라우저인 경우 네이버에서 제공하는 API 를 통해 아이피로 위치를 구한다.

사용 전 아래 주소로 네이버의 API키를 받는다.
(https://www.ncloud.com/product/applicationService/geoLocation)

<? 
	function makeSignature($secretKey, $method, $baseString, $timestamp, $accessKey)
	{
		$space = ' ';
		$newLine = "\n";
		$hmac = $method.$space.$baseString.$newLine.$timestamp.$newLine.$accessKey;
		$signautue = base64_encode(hash_hmac('sha256', $hmac, $secretKey,true));
		return $signautue;
	}

	if($_POST['order'] == 'geolocation')
	{
		$hostNameUrl = 'https://geolocation.apigw.ntruss.com';
		$requestUrl= '/geolocation/v2/geoLocation';
		$accessKey = 'accessKey를 입력해주세요.';
		$secretKey = 'secretKey를 입력해주세요.';

		$ip = $_SERVER['REMOTE_ADDR'];
		$timestamp = round(microtime(true) * 1000);

		$baseString = $requestUrl.'?ip='.$ip.'&ext=t&responseFormatType=json';

		$signautue = makeSignature($secretKey, 'GET', $baseString, $timestamp, $accessKey);
		$url = $hostNameUrl.$baseString;

		$is_post = false;
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_POST, $is_post);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$headers = array();
		$headers[] = 'X-NCP-APIGW-TIMESTAMP: '.$timestamp;
		$headers[] = 'X-NCP-IAM-ACCESS-KEY: '.$accessKey;
		$headers[] = 'X-NCP-APIGW-SIGNATURE-V2: '.$signautue;

		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
		$response = json_decode(curl_exec ($ch), true);

		if($response['geoLocation'])
		{
			$lat = $response['geoLocation']['lat'];
			$lng = $response['geoLocation']['long'];
		}else{
			$lat = 37.535053;
			$lng = 127.147263;
		}

		echo json_encode(array('latitude'=>$lat, 'longitude'=>$lng));
		exit;
	}

?>
<html lang="ko">
<head>
	<meta charset="UTF-8">
	<title>위치 계산중...</title>
</head>
<body>
<div style="width: 100%; text-align: center; display: inline-block; ">
	<p>원활한 이용을 위해 사용자의 위치를 계산 중입니다.</p>
	<p>위치 확인 권한을 <font color="RED"><strong>허용</strong></font>해주시길 바랍니다.</p>
</div>

<script>
	function setPositionByGeo(pos)
	{
		document.cookie = "latitude=" + pos.coords.latitude;
		document.cookie = "longitude=" + pos.coords.longitude;

		location.href = "<?=$_GET['url'] ? $_GET['url'] : '/'?>";
	}

	function setPositionByIP()
	{
		var xhr = new XMLHttpRequest();
		var dat = new FormData();

		dat.append("order", "geolocation");

		xhr.open("POST", window.location.pathname);
		xhr.send(dat);

		xhr.onload = function()
		{
			if(xhr.status === 200 || xhr.status === 201)
			{
				var res = JSON.parse(xhr.responseText);

				if(res.latitude&&res.longitude)
				{
					document.cookie = "latitude=" + res.latitude;
					document.cookie = "longitude=" + res.longitude;


					location.href = "<?=$_GET['url'] ? $_GET['url'] : '/'?>";
				}
			}
		};
	}

	window.onload = function() {
		if (navigator.geolocation)
			navigator.geolocation.getCurrentPosition(setPositionByGeo, setPositionByIP);
		else
			setPositionByIP();
	}
</script>
</body>
</html>

Similar Posts

  • |

    HTTP 접속 정보 기록

    OpenAPI 이용시 테스트 겸 접속 정보가 제대로 됬는지 확인용 접속시 메소스값, 호스트, POST 값 [PHP] <? $log = $_SERVER[‘REQUEST_METHOD’].’ ‘.$_SERVER[‘HTTP_HOST’].$_SERVER[‘REQUEST_URI’].”nn”; foreach($_SERVER as $k => $v) { if($k==’HTTP_HOST’) continue; if(substr($k, 0,5)!=’HTTP_’) continue; $log .= ‘$k: $v’.”n”; } $log .= “n”; $post = array_map(‘urldecode’, explode(‘&’, file_get_contents(‘php://input’))); foreach($post as $v) { $log .= “$vn”; } $log .= “———————————–n”;…

  • |

    PHP로 만든 단순한 CDN 서비스 모듈

    트래픽 부하를 줄이기 위해 CloudFlare 를 사용하였는데 연결위치가 LAX(로스엔젤레스)라 속도가 많이 느려지는것을 확인하고 급하게 CDN 형태로 사용하고자 만들었습니다. 해당 서버는 도쿄(Vultr)에 위치해 있습니다. 원리는 kilho.net/{파일} 을 cdn.kilho.net/{파일} 로 연결하여 메인 호스팅의 트래픽을 분산합니다. [PHP] <? $cfg[‘url’] = ‘kilho.net’; $cfg[‘cache’] = ‘../data/cache’; $url = $_SERVER[‘REQUEST_SCHEME’].’://’.$cfg[‘url’].$_SERVER[‘REQUEST_URI’]; $url_arr = parse_url($url); switch($_SERVER[‘REQUEST_METHOD’]) { case ‘GET’: $filename = $cfg[‘cache’].$url_arr[‘path’]; $dirname…

  • Go 언어 설치 – 윈도우

    1. https://golang.org/dl/ 에서 다운로드 및 설치 2. 작업 폴더 생성 (예: d:\source\Go) 3. 하위에 bin, pkg, src 폴더 생성 4. 윈도우 제어판 -> 시스템 -> 고급 시스템 설정 -> 환경 변수 5. 사용자 변수 그룹에서 GOPATH 에 작업 폴더 입력 6. 변수 이름에 GOPATH 입력 7. 변수 값에 작업 폴더 입력(예: d:\source\Go) 8. 확인시 cmd…

  • |

    워드프레스, 그누보드 연동

    현재 길호넷에서 워드프레스와 그누보드를 연동한 방식입니다. 사이트를 좀 더 안정화를 시킨 후 소스를 공개하려고 하였는데, 그누보드 사용자분의 요청(?)으로 급조하여 만든걸 올립니다. (http://sir.co.kr/bbs/board.php?bo_table=cm_free&wr_id=741180) 추후, 그누보드의 head.php, tail.php 에서 워드프레스에서 생성된 페이지를 직접 불러들이고, 캐쉬 처리 및 컨텐츠 영역을 상하로 나눈 후 출력하는것을 생각하고 있습니다. 워드프레스 회원 DB 를 기반으로 그누보드와 연동되어, 게시판 글 작성시 워드프레스의 로그인에…

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다