You can build a working speedometer with nothing but a web page and the Geolocation API. Getting a number on screen takes ten lines. Getting a number people trust takes a bit more. Here's what fills the gap between the two.
1. Start with watchPosition
const id = navigator.geolocation.watchPosition(onFix, onError, {
enableHighAccuracy: true, // ask for GPS, not just Wi-Fi/cell
maximumAge: 0, // never reuse a cached fix
timeout: 15000
});
A few things to know up front:
- It only works on HTTPS (or localhost).
- The browser shows a permission prompt the first time.
- Most phones deliver roughly one fix per second once GPS has locked.
2. Prefer coords.speed, fall back to distance
Each fix gives you coords.speed in metres per second. On phones with real GPS this value comes from the Doppler shift in the satellite signals, which is far steadier than measuring the gap between two positions a few metres apart.
But coords.speed can be null, so keep a fallback:
function haversine(a, b) {
const R = 6371000, toRad = d => d * Math.PI / 180;
const dLat = toRad(b.lat - a.lat), dLon = toRad(b.lon - a.lon);
const h = Math.sin(dLat / 2) ** 2 +
Math.cos(toRad(a.lat)) * Math.cos(toRad(b.lat)) * Math.sin(dLon / 2) ** 2;
return 2 * R * Math.asin(Math.sqrt(h)); // metres
}
const posOf = f => ({ lat: f.coords.latitude, lon: f.coords.longitude });
function speedFrom(prev, fix) {
if (fix.coords.speed != null) return fix.coords.speed;
if (!prev) return 0;
const dt = (fix.timestamp - prev.timestamp) / 1000;
return dt > 0 ? haversine(posOf(prev), posOf(fix)) / dt : 0;
}
3. Filter the junk
Raw GPS is noisy. Three filters make the biggest difference:
-
Accuracy gate.
coords.accuracyis the phone's own error estimate in metres. If it's worse than about 50 m, mark the signal as weak and don't add distance. - Impossible jumps. If a fix implies an acceleration no vehicle could manage, drop it.
- Standstill threshold. When the signal is weak, positions wander even if you're parked. Treating anything under about 7 km/h as stationary stops that drift from adding fake distance.
4. Smooth the needle
An exponential moving average is enough to stop the display jittering:
let smooth = 0;
const ALPHA = 0.3;
function update(rawMs) {
smooth = ALPHA * rawMs + (1 - ALPHA) * smooth;
render(smooth * 3.6); // m/s to km/h
}
Too much smoothing makes the reading lag under hard braking, so tune ALPHA with real drives, not a desk.
5. Average only the moving time
Users expect "average speed" to mean average while moving. Accumulate time only while speed is above your standstill threshold, or a long red light will drag the average down.
6. Keep the screen on
Mobile browsers pause geolocation when the screen turns off. The Screen Wake Lock API keeps it alive while the page is visible:
let lock;
async function keepAwake() {
try { lock = await navigator.wakeLock.request('screen'); } catch (_) {}
}
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'visible') keepAwake();
});
7. Keep it private
All of this runs on the device. There's no reason to send coordinates to a server just to show a speed, and users notice when you don't.
See it in a finished app
If you want to see these ideas working together, SpeediDash is a free GPS speedometer that runs entirely in the browser, with dial, digital, map and HUD views and nothing uploaded. Open it on your phone, go outside, and compare the numbers with your car's dashboard.
Top comments (0)