บทนำ
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 (เกินเวลา)