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

วิธีหาตำแหน่งที่ตั้งด้วย HTML5 Geolocation API

HTML5 Geolocation API ให้เว็บไซต์เข้าถึงตำแหน่งที่ตั้งของผู้ใช้ (latitude, longitude) ส่งไป backend เพื่อหาสถานที่ใกล้เคียง แสดงบนแผนที่ ฯลฯ

API ทำงานผ่าน property navigator.geolocation (Geolocation object)

เมธอดหลัก

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

ตัวอย่าง: หาตำแหน่งปัจจุบัน

<!DOCTYPE HTML> <html>
  <head>
    <script type="text/javascript">
      function showLocation(position) {
        var latitude = position.coords.latitude;
        var longitude = position.coords.longitude;
        alert("Latitude: " + latitude + " Longitude: " + longitude);
      }
      function errorHandler(err) {
        if(err.code == 1) alert("Error: Access is denied!");
        else if(err.code == 2) alert("Error: Position is unavailable!");
      }
      function getLocation(){
        if(navigator.geolocation){
          var options = {timeout: 60000, enableHighAccuracy: true};
          navigator.geolocation.getCurrentPosition(showLocation, errorHandler, options);
        } else {
          alert("Sorry, browser does not support geolocation!");
        }
      }
    </script>
  </head>
  <body>
    <form>
      <input type="button" onclick="getLocation();" value="Get Location"/>
    </form>
  </body>
</html>

Position Object Properties

Propertyคำอธิบาย
coords.latitudeละติจูด (องศา)
coords.longitudeลองจิจูด (องศา)
coords.accuracyความแม่นยำ (เมตร)
coords.altitudeความสูงจากระดับน้ำทะเล (เมตร)
coords.speedความเร็ว (เมตร/วินาที)
coords.headingทิศทาง (องศา จากเหนือ)

ข้อกำหนดสำคัญ

  • ต้องใช้ HTTPS (localhost ยกเว้น)
  • ต้องขอ permission จากผู้ใช้
  • บน mobile ให้เพิ่ม enableHighAccuracy: true เพื่อใช้ GPS