HTML5 Geolocation clearWatch() API
Geolocation是HTML5中的API,可以用來獲取用戶的GIF位置。愛掏網 - it200.com它可以獲取用戶位置的精確度,但其可用性因為瀏覽器的差異而有所不同。愛掏網 - it200.com
示例代碼1:獲取用戶位置
// 獲取用戶位置
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
console.log("Your location is: " + lat + "," + lng);
});
} else {
console.log("Geolocation is not supported by this browser.");
}
示例代碼2:設定位置精確度
// 設定位置精確度
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
function success(pos) {
var crd = pos.coords;
console.log('Your current position is:');
console.log(`Latitude : {crd.latitude}`);
console.log(`Longitude:{crd.longitude}`);
console.log(`More or less {crd.accuracy} meters.`);
}
function error(err) {
console.warn(`ERROR({err.code}): ${err.message}`);
}
navigator.geolocation.getCurrentPosition(success, error, options);
clearWatch() API是什么?
clearWatch()是Geolocation API中的函數,用來停止正在進行中的GIF位置的跟蹤。愛掏網 - it200.com當watchPosition()被調用時,它將返回一個唯一的ID。愛掏網 - it200.com這個ID可以被clearWatch()函數使用,以便在任何時候停止GIF位置的跟蹤。愛掏網 - it200.com
示例代碼3:停止GIF位置的跟蹤
// 停止GIF位置的跟蹤
var id = navigator.geolocation.watchPosition(
function success(pos) {
var crd = pos.coords;
console.log('Your current position is:');
console.log(`Latitude : {crd.latitude}`);
console.log(`Longitude:{crd.longitude}`);
console.log(`More or less {crd.accuracy} meters.`);
},
function error(err) {
console.warn(`ERROR({err.code}): ${err.message}`);
},
{
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
}
);
navigator.geolocation.clearWatch(id); // 停止跟蹤
在上面的代碼中,我們首先調用watchPosition()函數來跟蹤用戶的GIF位置。愛掏網 - it200.com該函數返回一個id,它可以用于停止位置的跟蹤。愛掏網 - it200.com我們使用clearWatch()來停止跟蹤。愛掏網 - it200.com
結論
Geolocation API提供了一種簡單的方法來獲取用戶的GIF位置。愛掏網 - it200.com在我們的示例代碼中,我們看到了如何使用getCurrentPosition()和watchPosition()方法來獲取位置。愛掏網 - it200.com我們還看到了如何使用clearWatch()函數來停止正在進行中的GIF位置的跟蹤。愛掏網 - it200.com這使得Geolocation API成為開發地理位置應用程序的有用工具。愛掏網 - it200.com
聲明:所有內容來自互聯網搜索結果,不保證100%準確性,僅供參考。如若本站內容侵犯了原著者的合法權益,可聯系我們進行處理。