บทนำ
HTML5 Geolocation API ให้ JavaScript เข้าถึงตำแหน่งภูมิศาสตร์ของผู้ใช้ (Latitude/Longitude) ผ่าน navigator.geolocation
เมธอดหลัก
| เมธอด | คำอธิบาย |
getCurrentPosition(success, error, options) | ดึงตำแหน่งปัจจุบันครั้งเดียว |
watchPosition(success, error, options) | ติดตามตำแหน่งต่อเนื่อง (Return watchID) |
clearWatch(watchID) | ยกเลิกการติดตาม |
อ็อบเจกต์ Position
| Property | Type | คำอธิบาย |
coords.latitude | Number | ละติจูด (-90 ถึง +90) |
coords.longitude | Number | ลองจิจูด (-180 ถึง +180) |
coords.accuracy | Number | ความแม่นยำ (เมตร) |
coords.altitude | Number|null | ความสูงจากระดับน้ำทะเล (เมตร) |
coords.altitudeAccuracy | Number|null | ความแม่นยำความสูง |
coords.heading | Number|null | ทิศทาง (องศา จากเหนือ) |
coords.speed | Number|null | ความเร็ว (เมตร/วินาที) |
timestamp | DOMTimeStamp | เวลาที่ได้ตำแหน่ง |
ตัวอย่าง: ติดตามตำแหน่ง (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