Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> HTML

HTML Geolocation API: ดึงตำแหน่งที่ตั้งผู้ใช้เรียลไทม์

HTML Geolocation API คืออะไร?

Geolocation API ใช้ดึง **ตำแหน่งทางภูมิศาสตร์แบบเรียลไทม์** ของผู้ใช้ (Latitude, Longitude) ผ่าน JavaScript **ต้องได้รับอนุญาตจากผู้ใช้ก่อน** ใช้งานได้กับ HTTPS เท่านั้น (Chrome 50+, Firefox, Safari, Edge)

รูปแบบการใช้งาน (Syntax)

navigator.geolocation.getCurrentPosition(successCallback, errorCallback, options)

ออบเจ็กต์ Position (คืนค่าเมื่อสำเร็จ)

องศาทศนิยม
คุณสมบัติ คำอธิบาย หน่วย
coords.latitudeละติจูด (Latitude)
coords.longitudeลองจิจูด (Longitude)องศาทศนิยม
coords.accuracyความแม่นยำของตำแหน่งเมตร
coords.altitudeความสูงจากระดับน้ำทะเลเฉลี่ยเมตร (อาจเป็น null)
coords.altitudeAccuracyความแม่นยำของความสูงเมตร (อาจเป็น null)
coords.headingทิศทางการเคลื่อนที่ (จากเหนือตามเข็มนาฬิกา)องศา (อาจเป็น null)
coords.speedความเร็วเมตร/วินาที (อาจเป็น null)
timestampเวลาที่ได้รับตำแหน่งDate object

ตัวอย่างครบวงจร: ดึงตำแหน่ง, แสดงบนแผนที่, จัดการข้อผิดพลาด

<!DOCTYPE html>
<html>
<head>
  <title>HTML Geolocation Demo</title>
  <style>
    * { padding: 2px; margin: 5px; }
    form { width: 70%; margin: 0 auto; text-align: center; }
    input[type="button"] { border-radius: 10px; padding: 8px 16px; }
    #mapLink { color: #0066cc; text-decoration: none; font-weight: bold; }
  </style>
</head>
<body>
  <form>
    <fieldset>
      <legend>HTML Geolocation API</legend>
      <input type="button" value="📍 อัปเดตตำแหน่ง" onclick="getLocation()">
      <input type="button" value="🗺️ เปิดใน Google Maps" onclick="openMap()" disabled id="mapBtn">
      <div id="status">กดปุ่ม "อัปเดตตำแหน่ง" เพื่อเริ่มต้น</div>
      <div>
        <span id="lat">Latitude: -</span> | 
        <span id="lon">Longitude: -</span>
      </div>
      <div>ความแม่นยำ: <span id="acc">-</span> เมตร</div>
    </fieldset>
  </form>

  <script>
    var latEl = document.getElementById('lat');
    var lonEl = document.getElementById('lon');
    var accEl = document.getElementById('acc');
    var statusEl = document.getElementById('status');
    var mapBtn = document.getElementById('mapBtn');
    var currentPos = null;

    function getLocation() {
      statusEl.textContent = '📡 กำลังดึงตำแหน่ง...';
      mapBtn.disabled = true;
      
      if (!navigator.geolocation) {
        statusEl.textContent = '❌ เบราว์เซอร์ไม่รองรับ Geolocation';
        return;
      }

      navigator.geolocation.getCurrentPosition(
        onSuccess,
        onError,
        {
          enableHighAccuracy: true,  // ใช้ GPS หากมี
          timeout: 10000,            // 10 วินาที
          maximumAge: 0              // ไม่ใช้ cache
        }
      );
    }

    function onSuccess(position) {
      currentPos = position;
      var coords = position.coords;
      latEl.textContent = 'Latitude: ' + coords.latitude.toFixed(6);
      lonEl.textContent = 'Longitude: ' + coords.longitude.toFixed(6);
      accEl.textContent = coords.accuracy ? coords.accuracy.toFixed(1) : 'N/A';
      statusEl.textContent = '✅ ได้ตำแหน่งแล้ว!';
      statusEl.style.color = 'green';
      mapBtn.disabled = false;
    }

    function onError(error) {
      var msg = '';
      switch(error.code) {
        case error.PERMISSION_DENIED:
          msg = '🚫 ผู้ใช้ปฏิเสธการเข้าถึงตำแหน่ง';
          break;
        case error.POSITION_UNAVAILABLE:
          msg = '📡 ไม่สามารถดึงตำแหน่งได้ (GPS สัญญาณอ่อน/ไม่มี)';
          break;
        case error.TIMEOUT:
          msg = '⏱️ หมดเวลารอตอบสนอง';
          break;
        case error.UNKNOWN_ERROR:
          msg = '❓ เกิดข้อผิดพลาดไม่ทราบสาเหตุ';
          break;
      }
      statusEl.textContent = msg;
      statusEl.style.color = 'red';
      mapBtn.disabled = true;
    }

    function openMap() {
      if (!currentPos) return;
      var lat = currentPos.coords.latitude;
      var lon = currentPos.coords.longitude;
      var url = 'https://www.google.com/maps/@' + lat + ',' + lon + ',15z';
      window.open(url, '_blank');
    }
  </script>
</body>
</html>

เมธอดเพิ่มเติมของ Geolocation

เมธอด คำอธิบาย
watchPosition(success, error, options)ติดตามตำแหน่งต่อเนื่อง (คืน watchId) - ใช้สำหรับ Navigation
clearWatch(watchId)หยุดการติดตามตำแหน่ง

ตัวอย่าง watchPosition (ติดตามตำแหน่ง)

var watchId = navigator.geolocation.watchPosition(
  function(pos) { console.log('ตำแหน่งใหม่:', pos.coords.latitude, pos.coords.longitude); },
  function(err) { console.error(err); },
  { enableHighAccuracy: true }
);

// หยุดติดตามเมื่อไม่ต้องการแล้ว
// navigator.geolocation.clearWatch(watchId);

ข้อจำกัดและแนวทางปฏิบัติ

  • HTTPS บังคับ: ไม่ทำงานบน HTTP (localhost 除く)
  • ต้องได้รับอนุญาต: ผู้ใช้ต้องกด Allow
  • ความแม่นยำแตกต่างกัน: GPS (ดีที่สุด) > WiFi > Cell Tower > IP Address
  • ประหยัดแบตเตอรี่: ใช้ maximumAge และ timeout ให้เหมาะสม ปิด watchPosition เมื่อไม่ใช้
  • Privacy: แจ้งผู้ใช้ชัดเจนว่าทำไมต้องการตำแหน่ง และใช้ทำอะไร