The car on a ride-hailing map is not where the driver is. It is where the app guesses the driver is.
The driver's phone reports a GPS position every few seconds, not continuously. If the rider's app drew each report the moment it arrived, the car would teleport from point to point. So the app animates the car from one report toward the next, and the animation is invented. Most of the time the invention is good. Sometimes the car takes a strange turn, cuts through a building and snaps back to the road. The guess was off, and the next real position corrected it.
I don't know how Uber, Careem or any other app implements this, and each one tunes its own details. This article describes the general pattern and one way to build it in Kotlin with Flow, including the numbers you have to choose and the ways it fails.
Never render raw pings
A ping is a measurement taken at a time. Drawing it means claiming the car was there now, but by the time it travelled from the driver's phone through a server to the rider's phone, it is already old.
The fix is to animate from the last known position to the new one, over roughly the time until the next update is expected. The car is always moving toward the most recent fact and never standing on it.
Two things follow. First, you display the past, slightly: the car you see is a few seconds behind the driver, so don't use the display position for anything that must be exact, such as arrival detection. Second, the animation duration matters. If it is shorter than the real gap between pings, the car arrives early and waits, which looks like stop-and-go. If it is longer, the next ping arrives mid-glide and the car lurches.
So don't hard-code the duration. Track the real gaps between accepted updates, smooth them (an exponential moving average is enough) and cap the result, so one long silence does not turn into a very slow glide.
Trust timestamps, not arrival order
Networks reorder and batch. After a tunnel, three updates can arrive together. A retry can deliver an old position after a new one. If you animate in arrival order, the car drives backwards for a moment.
Every fix needs the time it was measured. On Android, Location.getElapsedRealtimeNanos() is a monotonic device timestamp, but it is only comparable within one boot of the driver's phone, so have the server stamp the update as well. Drop anything not newer than the newest one you have accepted:
data class Fix(val lat: Double, val lng: Double, val timeMs: Long)
fun Flow<Fix>.dropStale(): Flow<Fix> = flow {
var newest = Long.MIN_VALUE
collect { fix ->
if (fix.timeMs > newest) {
newest = fix.timeMs
emit(fix)
}
}
}
A stale update is not worth correcting toward. It describes a place the car has already left.
Move along the road, not in a straight line
If the car glides in a straight line between two pings, it cuts every corner between them. That is the building you sometimes see it drive through. For a trip with a known route, the general fix is to interpolate along the route polyline instead of across the gap.
That requires map-matching: projecting each raw position onto the route. For a trip in progress, you have the polyline already, and the matching is cheap:
- Find the nearest point on the route to the raw position.
- Only search ahead of the last matched point, with a small allowance backwards.
- Interpolate along the polyline from the previous match to the new one.
The second step carries most of the value. GPS error near a junction can place the driver closer to a parallel street, or to the opposite carriageway. If the search can jump anywhere on the route, the car skips ahead or flips. A search window that only moves forward keeps progress monotonic. When the route is unknown, services such as Google's Roads API (snap to roads) or Mapbox's Map Matching API can snap a sequence of points to the road network, at the cost of a network call and some latency.
Map-matching can also be confidently wrong: a driver who leaves the route is, for a moment, matched back onto it. Set a distance beyond which you stop trusting the polyline and fall back to the raw position, and test it with a driver who takes a different road.
Derive heading from the path, then smooth it
The raw bearing in a GPS fix comes from the device, and it jitters, especially when the car is slow or stopped. A car icon that spins at a red light looks broken.
Compute heading from the path you are drawing, and only update it when the car has actually moved some metres. Then smooth the rotation, interpolating the shortest way round the circle so it does not swing 350 degrees to go from 5 to 355:
fun smoothAngle(current: Double, target: Double, alpha: Double): Double {
// Signed shortest difference in the range [-180, 180).
val diff = ((target - current + 540.0) % 360.0) - 180.0
return (current + diff * alpha + 360.0) % 360.0
}
fun bearingDeg(fromLat: Double, fromLng: Double, toLat: Double, toLng: Double): Double {
val dx = (toLng - fromLng) * Math.cos(Math.toRadians(fromLat))
val dy = toLat - fromLat
return (Math.toDegrees(Math.atan2(dx, dy)) + 360.0) % 360.0
}
The bearing function uses a flat approximation: fine over tens of metres, wrong over long distances.
Animate with Flow
Here is the core of the glide. The important choice is collectLatest: when a new fix arrives, the animation for the previous one is cancelled, and the next one starts from where the car is displayed, not from where the previous fix was. That one detail is what makes corrections gentle.
data class CarState(
val lat: Double,
val lng: Double,
val bearingDeg: Double,
val stale: Boolean = false,
)
private fun lerp(a: Double, b: Double, t: Double) = a + (b - a) * t
fun Flow<Fix>.glide(
glideMs: () -> Long, // smoothed gap between updates
staleAfterMs: Long = 10_000,
frameMs: Long = 16, // use a frame clock in production
): Flow<CarState> = channelFlow {
var shown: CarState? = null
this@glide.dropStale().collectLatest { fix ->
val from = shown
?: CarState(fix.lat, fix.lng, 0.0).also { shown = it; send(it) }
val steps = (glideMs() / frameMs).coerceAtLeast(1)
val moved = from.lat != fix.lat || from.lng != fix.lng
val target = if (moved) bearingDeg(from.lat, from.lng, fix.lat, fix.lng) else from.bearingDeg
for (i in 1..steps) {
val t = i / steps.toDouble()
val next = CarState(
lat = lerp(from.lat, fix.lat, t),
lng = lerp(from.lng, fix.lng, t),
bearingDeg = smoothAngle((shown ?: from).bearingDeg, target, alpha = 0.15),
)
shown = next
send(next)
delay(frameMs)
}
// Silence: if nothing newer arrives, this block stays suspended and
// collectLatest cancels it when it does.
delay(staleAfterMs)
shown?.let { send(it.copy(stale = true)) }
}
}
This is a sketch. In an app I would drive the frames from the UI frame clock (withFrameNanos in Compose, ValueAnimator in views) instead of delay(16). The structure stays the same.
Some weaknesses. collectLatest drops the intermediate fixes of a burst, so after a tunnel the car glides straight to the newest point and can cut a corner. If that matters, buffer the burst and play it through at increased speed. The smoothing factor of 0.15 is applied per frame, so it depends on the frame rate. And the glide is linear, which suits constant speed but not a car that has just braked.
Plan for silence
Updates stop. The driver goes through a tunnel, loses signal, or the app is backgrounded. The tempting behavior is to keep the car moving, because a frozen car looks like a bug.
Extrapolation is acceptable for a short time: continue along the route at the last known speed for roughly one expected interval, then stop. A car that keeps driving is a trip you invented, and the rider will act on it by walking to the pickup point or deciding whether to wait.
In the code above, delay(staleAfterMs) followed by stale = true is where that goes (extrapolation would sit just before it). What the UI does with the flag matters more than the flag: dim the car, show the time of the last update, and do not show an ETA that implies precision you no longer have. When the next fix arrives, collectLatest cancels the wait and the car glides back into place.
Correct gently, unless the error is large
When a real fix disagrees with where you drew the car, easing toward it looks natural. The code does this already, because every glide starts from the displayed position.
There is a limit. If the displayed position and the new fix are far apart (a different road, a reconnect after a long silence), gliding across that distance shows the car driving through the city. Beyond a distance threshold, jump instead. The threshold is a product decision based on your city's block sizes and typical GPS error. I would start from a few hundred metres and tune against recorded trips.
Tune the update rate to what you can afford
The update rate is a budget, and the driver's phone pays for it. Frequent updates use battery and mobile data. On Android, the interval you request from the fused location provider is not exact: updates can come faster, slower or in batches. Design for jitter in the arrival times rather than assuming a clock tick.
Slower updates push work to the rider's phone: longer glides, more extrapolation, bigger corrections. Faster updates reduce the smoothing you need and raise the cost on the other side. I'd choose the slowest rate at which the correction jumps still look acceptable on recorded real trips, and consider making it adaptive: faster near the pickup point, slower on a long straight road.
Record real trips and replay them through the pipeline, with fixes and timestamps as input and the rendered path as output. It is the only way I know to tune these numbers without driving around.
There's a 43-second Arabic version of this in my «خلف الكواليس» series: https://youtube.com/shorts/DNluaevHEtQ
Top comments (3)
The "search only ahead of the last matched point" step is the one I would have gotten wrong — it is the detail that keeps a GPS wobble near a junction from flipping the car onto the parallel street. One thing I kept wondering about: after a tunnel, collectLatest drops the burst and the car glides straight to the newest fix. You mention buffering the burst and playing it through at increased speed — have you tried that in practice, and does the fast replay actually look better to a rider than one clean glide, or does it just look like the car suddenly speeding?
Thanks for waiting, Abdullah. My take: fast replay works when the gap is short. After a long tunnel, the car looks like it is racing, so I would cap the speed. For a big gap, one calm glide to the newest point is usually better. Worth testing both on a real route.
Thanks, Abdullah! Good question, I will get back to you with details.