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