<./>.dev./hood

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>