如何在 HTML5 中使用地理位置座標?
HTML5 地理位置 API 允許您與您喜愛的網站共享您的位置。Javascript 可以捕獲您的經緯度,並可以傳送到後端 Web 伺服器,並執行諸如查詢本地企業或在地圖上顯示您的位置等位置感知操作。地理位置座標指定裝置的地理位置。
地理位置方法 getCurrentPosition() 和 getPositionUsingMethodName() 指定檢索位置資訊的回撥方法。這些方法非同步呼叫到儲存完整位置資訊的 Position 物件。
Position 物件指定裝置當前的地理位置。位置表示為一組地理座標以及有關航向和速度的資訊。
Position 物件的屬性包括:
屬性 | 型別 | 描述 |
| coords | 物件 | 指定裝置的地理位置。位置表示為一組地理座標以及有關航向和速度的資訊。 |
| coords.latitude | 數字 | 以十進位制度數指定緯度估計值。值範圍為 [-90.00,+90.00]。 |
| coords.longitude | 數字 | 以十進位制度數指定經度估計值。值範圍為 [-180.00,+180.00]。 |
以下使用帶經緯度座標的 Position 物件:

geolocation 物件提供以下方法。它們都使用座標來檢索位置:
方法 | 描述 |
getCurrentPosition() | 此方法檢索使用者的當前地理位置。 |
watchPosition() | 此方法檢索有關裝置當前地理位置的定期更新。 |
clearWatch() | 此方法取消正在進行的 watchPosition 呼叫。 |
示例
您可以嘗試執行以下程式碼以瞭解如何使用地理位置並在 HTML5 中使用地理位置座標。它檢索有關裝置當前地理位置的定期更新。位置表示為一組地理座標以及有關航向和速度的資訊。
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
var watchID;
var geoLoc;
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 getLocationUpdate(){
if(navigator.geolocation){
// timeout at 60000 milliseconds (60 seconds)
var options = {timeout:60000};
geoLoc = navigator.geolocation;
watchID = geoLoc.watchPosition(showLocation, errorHandler, options);
} else{
alert("Sorry, browser does not support geolocation!");|
}
}
</script>
</head>
<body>
<form>
<input type="button" onclick="getLocationUpdate();" value="Watch Update"/>
</form>
</body>
</html>
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP