const MIN_MOVE_M = 5; const MAX_SPEED_M_S = 40; const SNAPBACK_NEAR_M = 15; const SNAPBACK_FAR_M = 200; const MAX_ACCURACY_M = 100; const RECENT_LIMIT = 24; function haversineMeters(a, b) { const R = 6371000; const toRad = (deg) => (deg * Math.PI) / 180; const dLat = toRad(b.lat - a.lat); const dLng = toRad(b.lng - a.lng); const x = Math.sin(dLat / 2) ** 2 + Math.cos(toRad(a.lat)) * Math.cos(toRad(b.lat)) * Math.sin(dLng / 2) ** 2; return R * 2 * Math.atan2(Math.sqrt(x), Math.sqrt(1 - x)); } function createLocationReportFilter() { return { last: null, recent: [] }; } function shouldAcceptLocationReport(state, point, nowMs) { const current = state && typeof state === 'object' ? state : createLocationReportFilter(); const lat = Number(point && point.lat); const lng = Number(point && point.lng); if (!Number.isFinite(lat) || !Number.isFinite(lng)) { return { accept: false, nextState: current }; } const acc = point && point.accuracy != null ? Number(point.accuracy) : null; if (acc != null && Number.isFinite(acc) && acc > MAX_ACCURACY_M) { return { accept: false, nextState: current }; } const sample = { lat, lng, t: Number(nowMs) }; if (!current.last) { return { accept: true, nextState: { last: sample, recent: [{ lat, lng }] }, }; } const dist = haversineMeters(current.last, sample); if (dist < MIN_MOVE_M) { return { accept: false, nextState: current }; } const dt = (sample.t - Number(current.last.t)) / 1000; if (dt > 0 && dist / dt > MAX_SPEED_M_S) { return { accept: false, nextState: current }; } const older = current.recent.slice(0, Math.max(0, current.recent.length - 1)); for (let i = 0; i < older.length; i += 1) { if (haversineMeters(older[i], sample) <= SNAPBACK_NEAR_M && dist >= SNAPBACK_FAR_M) { return { accept: false, nextState: current }; } } const recent = current.recent.concat([{ lat, lng }]); return { accept: true, nextState: { last: sample, recent: recent.length > RECENT_LIMIT ? recent.slice(recent.length - RECENT_LIMIT) : recent, }, }; } module.exports = { MIN_MOVE_M, MAX_SPEED_M_S, createLocationReportFilter, haversineMeters, shouldAcceptLocationReport, };