要实现每20米或3秒获取一次服务位置的功能,通常需要结合地理位置服务和定时任务来完成。以下是一个基本的实现思路,使用JavaScript和一些常见的Web API:
首先,你需要获取用户的当前位置。可以使用HTML5 Geolocation API来实现这一点。
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
} else {
console.log("Geolocation is not supported by this browser.");
}
}
function showPosition(position) {
console.log("Latitude: " + position.coords.latitude +
" Longitude: " + position.coords.longitude);
// 在这里处理位置数据
}
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
console.log("User denied the request for Geolocation.");
break;
case error.POSITION_UNAVAILABLE:
console.log("Location information is unavailable.");
break;
case error.TIMEOUT:
console.log("The request to get user location timed out.");
break;
case error.UNKNOWN_ERROR:
console.log("An unknown error occurred.");
break;
}
}
接下来,你需要设置一个定时任务,每隔3秒获取一次位置。同时,你还需要监听位置变化,当用户移动超过20米时也获取一次位置。
let watchId;
let lastPosition;
const distanceThreshold = 20; // 20米
const timeThreshold = 3000; // 3秒
function startTracking() {
watchId = navigator.geolocation.watchPosition(showPosition, showError, {
enableHighAccuracy: true,
timeout: timeThreshold,
maximumAge: 0
});
setInterval(getLocation, timeThreshold);
}
function stopTracking() {
navigator.geolocation.clearWatch(watchId);
}
function showPosition(position) {
if (lastPosition) {
const distance = calculateDistance(lastPosition, position.coords);
if (distance >= distanceThreshold) {
console.log("Distance threshold reached. New position:");
console.log("Latitude: " + position.coords.latitude +
" Longitude: " + position.coords.longitude);
}
}
lastPosition = position.coords;
}
function calculateDistance(pos1, pos2) {
const R = 6371e3; // metres
const φ1 = pos1.latitude * Math.PI / 180; // φ, λ in radians
const φ2 = pos2.latitude * Math.PI / 180;
const Δφ = (pos2.latitude - pos1.latitude) * Math.PI / 180;
const Δλ = (pos2.longitude - pos1.longitude) * Math.PI / 180;
const a =
Math.sin(Δφ / 2) * Math.sin(Δφ / 2) +
Math.cos(φ1) * Math.cos(φ2) *
Math.sin(Δλ / 2) * Math.sin(Δλ / 2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
const d = R * c; // in metres
return d;
}
最后,你需要提供启动和停止跟踪的接口。
startTracking(); // 开始跟踪
// stopTracking(); // 停止跟踪
领取专属 10元无门槛券
手把手带您无忧上云