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

วิธาใช้พิกัด Geolocation ใน HTML5


บทนำ

HTML5 Geolocation API ให้ JavaScript เข้าถึงตำแหน่งภูมิศาสตร์ของผู้ใช้ (Latitude/Longitude) ผ่าน navigator.geolocation

เมธอดหลัก

เมธอดคำอธิบาย
getCurrentPosition(success, error, options)ดึงตำแหน่งปัจจุบันครั้งเดียว
watchPosition(success, error, options)ติดตามตำแหน่งต่อเนื่อง (Return watchID)
clearWatch(watchID)ยกเลิกการติดตาม

อ็อบเจกต์ Position

PropertyTypeคำอธิบาย
coords.latitudeNumberละติจูด (-90 ถึง +90)
coords.longitudeNumberลองจิจูด (-180 ถึง +180)
coords.accuracyNumberความแม่นยำ (เมตร)
coords.altitudeNumber|nullความสูงจากระดับน้ำทะเล (เมตร)
coords.altitudeAccuracyNumber|nullความแม่นยำความสูง
coords.headingNumber|nullทิศทาง (องศา จากเหนือ)
coords.speedNumber|nullความเร็ว (เมตร/วินาที)
timestampDOMTimeStampเวลาที่ได้ตำแหน่ง

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

<!DOCTYPE HTML>
<html>
  <head>
    <script>
      var watchID, geoLoc;
      function showLocation(position) {
        var lat = position.coords.latitude;
        var lon = position.coords.longitude;
        alert("Latitude: " + lat + " Longitude: " + lon);
      }
      function errorHandler(err) {
        if (err.code == 1) alert("Error: Access denied!");
        else if (err.code == 2) alert("Error: Position unavailable!");
      }
      function getLocationUpdate() {
        if (navigator.geolocation) {
          var options = {timeout: 60000, enableHighAccuracy: true};
          geoLoc = navigator.geolocation;
          watchID = geoLoc.watchPosition(showLocation, errorHandler, options);
        } else {
          alert("Browser ไม่รองรับ Geolocation!");
        }
      }
    </script>
  </head>
  <body>
    <form>
      <input type="button" onclick="getLocationUpdate();" value="Watch Update" />
    </form>
  </body>
</html>

ตัวเลือก Options

  • enableHighAccuracy: true - ใช้ GPS (ช้า, ใช้แบต, แม่น)
  • timeout: 60000 - Timeout (มิลลิวินาที)
  • maximumAge: 0 - ไม่ใช้ Cache

ข้อควรระวัง

  • ต้องใช้ HTTPS (Localhost ได้)
  • ต้องขอ Permission จากผู้ใช้
  • บน Mobile ใช้ GPS/WiFi/Cell Tower