利用以下HTML 5程式碼可取得你目前所在的地理位置,不過前提是瀏覽器必須要支援以下的語法,比較舊型的瀏覽器已經無法支援HTML 5語法。
<!DOCTYPE html>
<meta charset=utf-8>
<head>
<title>HTML5 Geolocation API</title>
<script>
function $i(id) {return document.getElementById(id);}
</script>
</head>
<body>
<table style="border: solid 1px red;">
<thead>
<tr><th>Attribute</th><th>Value</th><th>Unit</th>
</tr>
</thead>
<tbody>
<tr>
<td>Latitude</td>
<td id="latitude"></td>
<td>degree</td>
</tr>
<tr>
<td>Longitude</td>
<td id="longitude"></td>
<td>degree</td>
</tr>
<tr>
<td>Altitude</td>
<td id="altitude"></td>
<td>m</td>
</tr>
<tr>
<td>Accuracy</td>
<td id="accuracy"></td>
<td>m</td>
</tr>
<tr>
<td>Altitude Accuracy</td>
<td id="altitudeAccuracy"></td>
<td>m</td>
</tr>
<tr>
<td>Heading</td>
<td id="heading"></td>
<td>degree/s</td>
</tr>
<tr>
<td>Speed</td>
<td id="speed"></td>
<td>m/s</td>
</tr>
<tr>
<td>Timestamp</td>
<td id="timestamp"></td>
<td>ms</td>
</tr>
</tbody>
</table>
<script>
if (navigator.geolocation) {
var geo=navigator.geolocation;
var option={
enableAcuracy:false,
maximumAge:0,
timeout:60000
};
geo.getCurrentPosition(successCallback,
errorCallback,
option
);
}
else {alert("This browser doesn't support geolocation function!");}
function successCallback(position) {
$i("latitude").innerHTML=position.coords.latitude;
$i("longitude").innerHTML=position.coords.longitude;
$i("altitude").innerHTML=position.coords.altitude;
$i("accuracy").innerHTML=position.coords.accuracy;
$i("altitudeAccuracy").innerHTML=position.coords.altitudeAccuracy;
$i("heading").innerHTML=position.coords.heading;
$i("speed").innerHTML=position.coords.speed;
$i("timestamp").innerHTML=position.timestamp;
}
function errorCallback(error) {
var errorTypes={
0:"Unknown Error",
1:"Permisson Denied",
2:"Position Unavailable",
3:"Timeout"
};
alert(errorTypes[error.code]);
alert("code=" + error.code + " " + error.message);
}
</script>
</body>
或者 errorCallback(error)也可以改寫成
function errorCallback(error) {
var error=0;
switch (error) {
case 0:
alert(error);
alert("code=" + error.code + " " + "Unknown Error");
break;
case 1:
alert(error);
alert("code=" + error.code + " " + "Permisson Denied");
break;
case 2:
alert(error);
alert("code=" + error.code + " " + "Position Unavailable");
break;
case 3:
alert(error);
alert("code=" + error.code + " " + "Timeout");
break;
default:
alert(error);
alert("code=" + error.code + " " + "Unknown Error");
break;
};
}