Lately I have been spending a lot of time around live location tracking, from the phone to the server to a line on a map. I am writing the lessons down in plain words so I do not forget them.
The first one is that a phone does not know where it is. It has a guess, and a number telling you how bad the guess is.
A GPS point is a circle, not a dot
Every fix the phone gives you has a latitude, a longitude, a timestamp, maybe a speed, and something called horizontal accuracy. That accuracy number is a radius. On Android it is a confidence radius, meaning the real position is inside that circle roughly two times out of three.
Indoors, or between tall buildings, the phone stops leaning on satellites and falls back to Wi-Fi or cell towers. Those fixes are easy to spot because the accuracy comes out as a suspiciously round number and the same coordinate often repeats several times in a row. A decent share of fixes on a normal day will simply be poor.
Background limits make it worse. When the phone sleeps, Android can throttle how often your app gets a location. If your logic treats a long silence as proof that someone went somewhere new, battery saving alone can invent movement that never happened.
The habit I settled on is to store every fix and decide what to draw later. Imprecise points can be counted and hidden behind a toggle, something like "a few imprecise locations not shown". I filter when drawing and never when saving, so the raw data stays untouched.
Sampling by how the phone is moving
The first instinct is a fixed interval, one fix every ten seconds. That drains the battery when the phone sits on a desk for hours, and it is still too slow to show a turn when you are in a vehicle.
What works better is choosing the interval from a motion state. Still, walking, in a vehicle, and maybe one more for when someone is actively watching the live map. Still means rare fixes with a minimum distance. Walking is more frequent. Vehicle is more frequent again. Low battery should drop you one level.
Switching needs care. If you change state instantly in both directions, a red light turns a vehicle into still, then back to vehicle, then still again. So the move up to a more active state is immediate, because you do not want to miss the start of a drive. The move down waits until the signal has held steady for a while. That small delay is hysteresis, and it removes most of the flicker.
function nextState(current: State, signal: State, stableForMs: number): State {
if (rank(signal) > rank(current)) return signal;
if (rank(signal) < rank(current) && stableForMs >= COOL_DOWN_MS) return signal;
return current;
}
The signal can come from the OS activity recognition API combined with plain speed from the fixes. I would rather have one small state machine gating the GPS than several alarms and geofences each nudging it on their own. The first is easy to debug and the second is not.
Android does not want your service alive
To keep tracking in the background on Android you generally need a foreground service with a visible notification. The user sees it all day. There is no way around that, and I do not think there should be.
Then you need to survive a reboot. You need to notice when the service is alive but the location callback has stopped firing. You need to guide the user toward unrestricted battery usage, and on many phones sold in India, toward the manufacturer's own autostart setting, which lives in a different place on every brand.
Permissions have a catch too. Background location can be declared in the manifest and still not be granted, so the app has to handle both cases.
Write to disk first, upload later
It is tempting to upload a fix the moment you get it. Then someone walks through a basement parking lot and a chunk of the trip is gone.
The safer shape is to write every event to local storage on the phone first. Upload is a separate job that reads from that storage in batches. If an upload fails, back off exponentially and honour Retry-After if the server sends it. The network must never decide whether a point gets recorded.
Make ingest safe to retry
Retries are guaranteed on mobile networks, so the server has to be idempotent, which means getting the same event twice changes nothing. The client generates an id per event, and the insert skips an id it has already seen. If the phone resends a batch, the server still acknowledges it.
insert into events (event_id, device_id, recorded_at, received_at, payload)
values (?, ?, ?, ?, ?)
on conflict (event_id) do nothing;
Device clocks are wrong more often than you would think, so I keep both recordedAt from the phone and receivedAt from the server and never overwrite either. Ordering by the phone's clock alone is asking for trouble.
I also learned not to treat a batch as all or nothing. If one malformed event fails the whole request and the client keeps retrying the same rows, a single bad row can block everything behind it. Judging each event on its own, and telling the client clearly which ones were accepted and which were not, keeps the queue moving.
Saying "I don't know"
Picture a phone reporting fine in the afternoon, then nothing for forty minutes, then it is back several kilometres away. What should the map draw in between?
The tempting answer is a straight line from A to B. It looks exactly as confident whether the gap was two minutes or two hours, and whether the person drove, walked, or the phone was simply switched off.
A better rule is to name a cause only when the data proves it, for example an explicit tracking-stopped event or a restart marker. Everything else is inference and should be labelled that way. If nothing arrived and there is no evidence, the honest label is unknown.
For the line itself, it helps to check whether the distance is plausible for the time elapsed. A walkable distance can get a dotted line marked as having no readings. A distance only a vehicle could cover can get a lighter route marked as likely. An impossible speed should get no line at all, just a flag.
I would rather show a gap than a wrong line that looks confident.
Cleaning the path
The accuracy filter removes most of the garbage, but not all of it. A few more checks help, and again none of them should delete anything. They only decide what to draw.
Skip repeated fixes that share a timestamp. Check implied speed, but reduce the distance between two fixes by their accuracy radii before dividing by time. A phone on a desk can report two points apart purely from noise, and without that adjustment the noise adds up to fake kilometres by the end of the day. Look for spikes that jump far away and snap straight back. Watch for slow drift while the phone's own motion sensor says it has not moved.
I tried a Kalman filter. It barely changed the results and did not fix the case that mattered, where one confident-looking bad reading pulls the line far off course. The smooth live pin people like on maps is usually animation between sparse pings, not denser GPS.
Where the cost goes
Storage is cheap. The real spend in a system like this tends to be maps, routing and road-snapping services billed per call. So snap only completed segments, sample less when still, cache lookups, and only do the expensive work for something a human is actually looking at.
Most days the map is right. Some days it says I was at home when I was at the tea stall down the road, and I have learnt to be okay with a screen saying "accurate to about 20 metres" instead of pretending it knows.