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

วิธาใช้ HTML5 Geolocation Latitude/Longitude API


บทนำ

Geolocation API ให้ JavaScript เข้าถึงตำแหน่งผู้ใช้ ผ่าน navigator.geolocation ต้องใช้ HTTPS

ตัวอย่าง: หาตำแหน่งปัจจุบัน (Get Current Position)

<!DOCTYPE HTML>
<html>
  <head>
    <script>
      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 getLocation() {
        if (navigator.geolocation) {
          var options = {timeout: 60000, enableHighAccuracy: true};
          navigator.geolocation.getCurrentPosition(showLocation, errorHandler, options);
        } else {
          alert("Browser ไม่รองรับ Geolocation!");
        }
      }
    </script>
  </head>
  <body>
    <form>
      <input type="button" onclick="getLocation();" value="Get Location" />
    </form>
  </body>
</html>

Position Coords Properties

Propertyคำอธิบาย
latitudeละติจูด (-90 ถึง +90)
longitudeลองจิจูด (-180 ถึง +180)
accuracyความแม่นยำ (เมตร)
altitudeความสูง (เมตร) หรือ null
altitudeAccuracyความแม่นยำความสูง
headingทิศทาง (องศา จากเหนือ) หรือ null
speedความเร็ว (เมตร/วินาที) หรือ null

Error Codes

  • 1 - PERMISSION_DENIED (ผู้ใช้ปฏิเสธ)
  • 2 - POSITION_UNAVAILABLE (GPS ไม่จับสัญญาณ)
  • 3 - TIMEOUT (เกินเวลา)