HTML5 Geolocation API 允許我們對喜歡的網站共享我們的位置。JavaScript 可以捕獲到緯度和經度,還可以發送給后端服務器,然后做一些位置感知的事情,比如查找本地企業或者在地圖上顯示我們的位置。

地理定位 APIs 是作為全局 navigator 對象的一個新屬性工作的。可以按照如下方式創建地理定位對象:
var geolocation = navigator.geolocation;
地理對象是一個允許組件檢索設備地理位置相關信息的服務對象。
navigator.geolocation.getCurrentPosition()
navigator.geolocation.watchPosition()
navigator.geolocation.clearWatch()
navigator.geolocation.getCurrentPosition(function(pos) {
var latitude = pos.coords.latitude;
var longitude = pos.coords.longitude;
alert("Your position: " + latitude + ", " + longitude);
});


Internet Explorer 9、Firefox、Chrome、Safari 以及 Opera 支持地理定位。注釋:對於擁有 GPS 的設備,比如 iPhone,地理定位更加精確。
if(navigator.geolocation){
//你的瀏覽器支持Geolocation API
} else{
//你的瀏覽器不支持Geolocation API
}
方法 | 描述 |
---|---|
getCurrentPosition() | 這個方法用於檢索用戶的當前地理位置。 |
watchPosition() | 這個方法用於檢索設備當前地理位置定期更新信息。 |
clearWatch() | 這個方法用於取消 watchPosition 方法調用。 |
示例
下面是一個使用上述方法的示例代碼:
functiongetLocation(){
var geolocation = navigator.geolocation;
geolocation.getCurrentPosition(showLocation, errorHandler);
}
這里的 showLocation 和 errorHandler 分別是用來獲取實際位置和處理錯誤的回調方法。
監視移動設備的位置變化
下面的例子展示 watchPosition() 方法。您需要一台精確的 GPS 設備來測試該例(比如 iPhone):
實例
<script> var x=document.getElementById("demo"); function getLocation() { if (navigator.geolocation) { navigator.geolocation.watchPosition(showPosition); } else{x.innerHTML="Geolocation is not supported by this browser.";} } function showPosition(position) { x.innerHTML="Latitude: " + position.coords.latitude + "<br />Longitude: " + position.coords.longitude; } </script>
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="utf-8">
<title>moyu's demo</title>
</head>
<body>
<script type="text/javascript"> navigator.geolocation.getCurrentPosition(function(pos){ console.log("當前地理位置的緯度: "+pos.coords.latitude); console.log("當前地理位置的經度: "+pos.coords.longitude); console.log("當前地理位置的精度: "+pos.coords.accuracy); }); var watchID = navigator.geolocation.watchPosition(function(pos){ console.log("當前位置變化的緯度: "+pos.coords.latitude); console.log("當前位置變化的經度: "+pos.coords.longitude); console.log("當前位置變化的精度: "+pos.coords.accuracy); navigator.geolocation.clearWatch(watchID); },function(){}); </script>
</body>
</html>
**
Description
The getCurrentPosition method retrieves the current geographic location of the device. The location is expressed as a set of geographic coordinates together with information about heading and speed. The location information is returned in a Position object.
Syntax
Here is the syntax of this method −
getCurrentPosition(showLocation, ErrorHandler, options);
Parameters
Here is the detail of parameters −
-
showLocation − This specifies the callback method that retrieves the location information. This method is called asynchronously with an object corresponding to the Position object which stores the returned location information.
-
ErrorHandler − This optional parameter specifies the callback method that is invoked when an error occurs in processing the asynchronous call. This method is called with the PositionError object that stores the returned error information.
-
options − This optional parameter specifies a set of options for retrieving the location information. You can specify (a) Accuracy of the returned location information (b) Timeout for retrieving the location information and (c) Use of cached location information.
Return value
The getCurrentPosition method does not return a value.
<!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) { // timeout at 60000 milliseconds (60 seconds) var options = {timeout:60000}; 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>
**
如果你希望跟蹤用戶的位置,那么可以使用另一個方法watchPosition()
。這個方法接收的參數與getCurrentPosition()
方法完全相同。實際上,watchPosition()
與定時調用getCurrentPosition()
的效果相同。在第一次調用watchPosition()
方法后,會取得當前位置,執行成功回調或者錯誤回調。
然后,watchPosition()
就地等待系統發出位置已改變的信號(它不會自己輪詢位置)。
調用watchPosition()
會返回一個數值標識符,用於跟蹤監控的操作。基於這個返回值可以取消監控操作,只要將其傳遞給clearWatch()
方法即可(與使用setTimeout()
和clearTimeout()
類似)。
例如:
var watchId = navigator.geolocation.watchPosition(function(position){
drawMapCenteredAt(position.coords.latitude, positions.coords.longitude);
}, function(error){
console.log("Error code: " + error.code);
console.log("Error message: " + error.message);
});
clearWatch(watchId);
以上例子調用了watchPosition()
方法,將返回的標識符保存在了watchId
中。然后,又將watchId
傳給了clearWatch()
,取消了監控操作。
Description
The watchPosition method retrieves periodic updates about the current geographic location of the device. The location is expressed as a set of geographic coordinates together with information about heading and speed.
The location information is returned in a Position object. Each update returns a new Position object.
Syntax
Here is the syntax of this method −
watchPosition(showLocation, ErrorHandler, options);
Parameters
Here is the detail of parameters −
-
showLocation − This specifies the callback method that retrieves the location information. This method is called asynchronously with an object corresponding to the Position object which stores the returned location information.
-
ErrorHandler − This optional paramter specifies the callback method that is invoked when an error occurs in processing the asynchronous call. This method is called with the PositionError object that stores the returned error information.
-
options − This optional paramter specifies a set of options for retrieving the location information. You can specify (a) Accuracy of the returned location information (b) Timeout for retrieving the location information and (c) Use of cached location information .
Return value
The watchPosition method returns a unique transaction ID (number) associated with the asynchronous call. Use this ID to cancel the watchPosition call and to stop receiving location updates.
Example
<!DOCTYPE HTML><head><html><scripttype="text/javascript">var watchID;var geoLoc;functionshowLocation(position){var latitude = position.coords.latitude;var longitude = position.coords.longitude;
alert("Latitude : "+ latitude +" Longitude: "+ longitude);}functionerrorHandler(err){if(err.code ==1){
alert("Error: Access is denied!");}elseif( err.code ==2){
alert("Error: Position is unavailable!");}}functiongetLocationUpdate(){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><inputtype="button"onclick="getLocationUpdate();"value="Watch Update"/></form></body></html>
**
Description
The clearWatch method cancels an ongoing watchPosition call. When cancelled, the watchPosition call stops retrieving updates about the current geographic location of the device.
Syntax
Here is the syntax of this method −
clearWatch(watchId);
Parameters
Here is the detail of parameters −
-
watchId − This specifies the unique ID of the watchPosition call to cancel. The ID is returned by the watchPosition call.
Return value
The clearWatch method does not return a value.
Example
<!DOCTYPE HTML><html><head><scripttype="text/javascript">var watchID;var geoLoc;functionshowLocation(position){var latitude = position.coords.latitude;var longitude = position.coords.longitude;
alert("Latitude : "+ latitude +" Longitude: "+ longitude);}functionerrorHandler(err){if(err.code ==1){
alert("Error: Access is denied!");}elseif( err.code ==2){
alert("Error: Position is unavailable!");}}functiongetLocationUpdate(){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!");}}functionstopWatch(){
geoLoc.clearWatch(watchID);}</script></head><body><form><inputtype="button"onclick="getLocationUpdate();"value="Watch Update"/><inputtype="button"onclick="stopWatch();"value="Stop Watch"/></form></body></html>
**
返回的位置對象的屬性
地理定位方法 getCurrentPosition() 和 getPositionUsingMethodName() 指定了檢索位置信息的回調方法。
這些方法使用一個存儲完整位置信息的 Position 對象異步調用。
這個 Position 對象指定了設備的當前地理位置。這個位置以一組帶有方向和速度信息的地理坐標表示。
下面的表格描述了 Position 對象的屬性。對於可選屬性,如果系統沒有提供值,則該屬性值為 null。
屬性 | 類型 | 描述 |
---|---|---|
coords | objects | 表示設備的地理位置。位置以一組帶有方向和速度信息的地理坐標表示。 |
coords.latitude | Number | 十進制的緯度估值。值范圍為 [-90.00, +90.00]。 |
coords.longitude | Number | 十進制的經度固執。值范圍為 [-180.00, +180.00]。 |
coords.altitude | Number | 【可選】 WGS-84 球面以上的海拔高度固執,以米為單位計算。 如果沒有相關數據則值為null 。 |
coords.accuracy | Number | 【可選】 以米為單位的緯度和經度精確估值。 |
coords.altitudeAccuracy | Number | 【可選】 以米為單位的海拔高度精確估值。 數值越大越不精確。 |
coords.heading | Number | 【可選】 相對正北方向設備以順時針方向運動計算的當前方向。 指南針的方向,0°表示正北,值為NaN 表示沒有檢測到數據。 |
coords.speed | Number | 【可選】 以米/每秒為單位的設備當前地面速度。 即每秒移動多少米,如果沒有相關數據則值為 |
timestamp | date | 檢索位置信息和創建 Position 對象的日期時間。 |
處理錯誤
地理定位是復雜的。非常需要我們捕獲任意錯誤並處理它。
地理定位方法 getCurrentPosition() 和 watchPosition() 可以使用一個提供 PositionError 對象的錯誤處理回調方法。
這個對象有下列兩屬性。
屬性 | 類型 | 描述 |
---|---|---|
code | Number | 錯誤碼。 |
message | String | 錯誤描述信息。 |
下面這個表格描述了 PositionError 對象可能返回的錯誤碼。
錯誤碼 | 常量 | 描述 |
---|---|---|
0 | UNKNOWN_ERROR | 由於未知錯誤,檢索設備位置信息失敗。 |
1 | PERMISSION_DENIED | 由於應用程序沒有權限使用位置服務,檢索設備位置信息失敗。 用戶拒絕了定位服務的請求。 |
2 | POSITION_UNAVAILABLE | 設備位置信息無法確定。沒有獲取正確的地理位置信息。 位置無效。 |
3 | TIMEOUT | 不能在給定的最大超時區間內檢索位置信息。 獲取位置的操作超時。 |
在error對象中,除"code"屬性表示出錯數字外,還可以通過"message"屬性獲取出錯的詳細文字信息。該屬性是一個字符串,包含與"code"屬性值相對應的錯誤說明信息。
實例
function showError(error) {
switch(error.code)
{
case error.PERMISSION_DENIED:
x.innerHTML="User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML="Location information is unavailable."
break;
case error.TIMEOUT:
x.innerHTML="The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
x.innerHTML="An unknown error occurred."
break;
}
}
**
下面是 getCurrentPosition() 方法的實際語法:
getCurrentPosition(callback, ErrorCallback, options)
其中第三個參數是指定一組檢索設備地理位置選項的 PositionOptions 對象。
下列選項可以指定為第三個參數:
屬性 | 類型 | 描述 |
---|---|---|
enableHighAccuracy | Boolean | 布爾值,是否想要檢索最精准的位置估值。默認值為 false。
屬性是指定瀏覽器或移動設備嘗試更精確地讀取經度和緯度,默認值為false。當這個屬性參數設置為true時,移動設備在定位計算上可能會花費更長時間,也容易導致消耗更多的移動設備電量。因此,如果無較高准確定位的需求,應該將參數設置為false或不設置。
|
timeout | Number | timeout 屬性就是 Web 應用程序要等待定位的毫秒數。 |
maximumAge | Number | 用於緩存位置信息的過期時間毫秒數。
最長有效期,在重復獲取地理位置時,此參數指定多久再次獲取位置。
默認為0,表示瀏覽器需要立刻重新計算位置。
|
如:
navigator.geolocation.getCurrentPosition(function(position){
drawMapCenteredAt(position.coords.latitude, positions.coords.longitude);
}, function(error){
console.log("Error code: " + error.code);
console.log("Error message: " + error.message);
}, {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 25000
});
這三個選項都是可選的,可以單獨設置,也可以與其他選項一起設置。
除非確實需要非常精確的信息,否則建議保持enableHighAccuracy
的false
值(默認值)。將這個選項設置為true
需要更長的時候,而且在移動設備上還會導致消耗更多電量。類似地,如果不需要頻繁更新用戶的位置信息,那么可以將maximumAge
設置為Infinity
,從而始終都使用上一次的坐標信息。
navigator.geolocation.getCurrentPosition(function(pos){
console.log("當前地理位置的緯度: "+pos.coords.latitude);
console.log("當前地理位置的經度: "+pos.coords.longitude);
console.log("當前地理位置的精度: "+pos.coords.accuracy);
},function(err){
if (err.code == 1) {
// access is denied
}
}, {maximumAge: 75000});
【】魔芋測試:(在瀏覽器中無效。)
火狐截圖:
**
**