html5 獲取你的位置信息

ps:

HTML5 Geolocation API 用於獲得用戶的地理位置。

鑑於該特性可能侵犯用戶的隱私,除非用戶同意,否則用戶位置信息是不可用的。

<!DOCTYPE html>
<html>
<body>
<p id="demo">點擊這個按鈕,獲得您的座標:</p>
<button οnclick="getLocation()">試一下</button>
<script>
var x=document.getElementById("demo");
function getLocation()
  {
  if (navigator.geolocation)
    {
    navigator.geolocation.getCurrentPosition(showPosition,showError);
    }
  else{x.innerHTML="Geolocation is not supported by this browser.";}
  }
function showPosition(position)
  {
  x.innerHTML="Latitude: " + position.coords.latitude + 
  "<br />Longitude: " + position.coords.longitude;	
  }
function showError(error)
  {
  switch(error.code) 
    {
    case error.PERMISSION_DENIED:
      x.innerHTML="User denied the request for Geolocation."
      break;
    case error.POSITION_UNAVAILABLE:
      x.innerHTML="Location information is unavailable."
      break;
    case error.TIMEOUT:
      x.innerHTML="The request to get user location timed out."
      break;
    case error.UNKNOWN_ERROR:
      x.innerHTML="An unknown error occurred."
      break;
    }
  }
</script>
</body>
</html>

以上點擊後,會返回當前位置的經緯度

getCurrentPosition() 方法 - 返回數據

若成功,則 getCurrentPosition() 方法返回對象。始終會返回 latitude、longitude 以及 accuracy 屬性。如果可用,則會返回其他下面的屬性。

屬性 描述
coords.latitude 十進制數的緯度
coords.longitude 十進制數的經度
coords.accuracy 位置精度
coords.altitude 海拔,海平面以上以米計
coords.altitudeAccuracy 位置的海拔精度
coords.heading 方向,從正北開始以度計
coords.speed 速度,以米/每秒計
timestamp 響應的日期/時間


發佈了48 篇原創文章 · 獲贊 1 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章