DEV Community

SpeediDash
SpeediDash

Posted on

Smoothing Live GPS Speed in JavaScript: Accuracy Gates, Deadbands and EMA

If you have ever wired navigator.geolocation.watchPosition straight into a speed readout, you already know the problem: the number will not sit still. It twitches while the device is stationary, spikes for no reason, and occasionally reports null. Here is how to get a reading you can actually put on screen.

Use the speed the device gives you

The first mistake is calculating speed yourself from consecutive coordinates. It seems reasonable, and it is wrong almost every time.

Position fixes carry error of a few metres even under open sky. If two fixes one second apart happen to land 5 metres apart purely from that error, distance over time reports 5 m/s, which is 18 km/h, while the phone sits on a desk.

The receiver already has a better answer. Modern GNSS chips derive velocity from the Doppler shift of the satellite carrier signal, which is far less noisy than differencing two noisy positions. The Geolocation API hands you that value directly:

const opts = { enableHighAccuracy: true, maximumAge: 0, timeout: 10000 };

navigator.geolocation.watchPosition(onFix, onError, opts);

function onFix(pos) {
  const { speed, accuracy } = pos.coords;   // speed is m/s, or null
  if (speed === null) return;               // device could not derive velocity
  if (accuracy > 25) return;                // fix too vague to trust
  render(smooth(speed) * 3.6);              // m/s -> km/h
}
Enter fullscreen mode Exit fullscreen mode

speed is in metres per second, and it is null whenever the device cannot work out a velocity. Do not quietly fall back to differencing positions when that happens. A gap in the readout is more honest than a fabricated number, and on most devices null only shows up for the first second or two.

Gate on accuracy before anything else

Every fix carries an accuracy value: the radius in metres of the 95% confidence circle. Indoors or in a city canyon this balloons, and a fix with 80 metres of uncertainty is not worth smoothing, it is worth dropping.

A threshold somewhere between 20 and 30 metres works well for pedestrian and vehicle speeds. Tighten it if your users are outdoors; loosen it if you would rather show a rough number than nothing.

Deadband the bottom end

Below walking pace, the signal is mostly noise. A simple floor removes nearly all visible twitching at a standstill:

let ema = null;
const ALPHA = 0.3;          // higher = more responsive, noisier
const FLOOR = 0.3;          // m/s, about 1 km/h

function smooth(v) {
  ema = ema === null ? v : ALPHA * v + (1 - ALPHA) * ema;
  return ema < FLOOR ? 0 : ema;
}
Enter fullscreen mode Exit fullscreen mode

That is an exponential moving average with a floor. It needs no history buffer, costs one multiply-add per fix, and converges quickly.

Do not over-smooth

This is the trap. A long averaging window produces a beautifully steady number that is also wrong: it lags real acceleration by seconds. On a speedometer that matters, because the moment people check the reading is exactly the moment the speed is changing.

With the EMA above, ALPHA around 0.3 keeps roughly a half-second of lag at a 1 Hz fix rate while removing most jitter. Drop it to 0.15 and the display is glassy but visibly behind. Raise it to 0.6 and you are nearly back to raw values.

A note on permissions

watchPosition requires a secure context, so HTTPS or localhost. The permission prompt fires on the first call, not on page load, so trigger it from a user gesture rather than on mount: a prompt that appears before the user has asked for anything gets denied far more often.

Also clear the watch when you are done. navigator.geolocation.clearWatch(id) matters more than it looks, because an orphaned high-accuracy watch keeps the GNSS radio awake and drains battery fast.

Putting it together

Accuracy gate, deadband, light EMA. Three small things, in that order, turn an unusable readout into something you can ship. If you want to see the end result behaving on real hardware, SpeediDash is a browser GPS speedometer built on exactly this pipeline, and the speedometer accuracy test compares the smoothed GPS figure against a vehicle's own dashboard reading.

Top comments (0)