A phone can produce a GPS fix every second. For a delivery or ride-hailing app, the obvious thing is to post each one to the server. The README of this package explains why that is a bad deal: sending every fix wastes battery, mobile data and server writes, and it still leaves a gap on the map as soon as the courier drives into a tunnel.
What the map needs is different from what the GPS produces. On a highway, a point every few seconds draws the route well. While the courier is parked, one point every few minutes is enough to say "still here". At a turn, a point should go out early so the line does not cut the corner. And when the network drops, the points should wait and be replayed in order.
throttled_location puts that policy between the GPS and your API. It decides when to send a position, what to send, and what to do while offline. It works with any location plugin, because it never reads the GPS itself.
What it does
The pieces. LocationFix holds lat, lon, accuracy, speed, heading, altitude, timestamp and isMocked, with JSON round-trip. ThrottledLocationReporter takes fixes from a LocationSource and sends batches through a LocationSink.
A sending policy. Every rule in ReportingPolicy can be configured, and they combine:
- a minimum interval between sends, as a hard floor;
- an interval that adapts to speed (
SpeedBands): by default 30 s when walking or idle, 15 s on a bike, 10 s in city traffic and 5 s on a highway; - a minimum distance moved, measured with Haversine, before an interval send;
- a heading-change threshold, so that turns are sent early;
- an accuracy filter that drops fixes with an accuracy radius worse than a set number of metres;
- an optional filter for mocked fixes;
- a stationary detector, which pauses sending and sends a heartbeat every N minutes, while leaving the radius is sent at once;
- a server override of the interval (such as
next_update_seconds), clamped to[minInterval, maxInterval].
A jitter filter. It rejects impossible jumps by checking that the speed between two fixes is plausible, after subtracting both accuracy radii. It re-syncs after N consistent fixes when the device really did move.
An offline backlog. It is bounded by count and by age. When full, it either drops the oldest points or downsamples, keeping every k-th point. When your Stream<bool> reports that connectivity is back, it is replayed oldest-first, in batches of a configurable size.
Pluggable storage. InMemoryBacklogStore is the default, and JsonFileBacklogStore (from io.dart) writes the file atomically. You can implement BacklogStore on anything else.
An in-flight guard. Sends never overlap. A failed send is retried with exponential backoff (RetryBackoff), and a reconnect retries at once.
Lifecycle and stats. start, pause, resume and stop, plus a statsStream with sent, queued, skipped and dropped counts by reason.
Testable. The clock is injectable and every timer uses dart:async, so the whole pipeline is deterministic under fake_async. The package is pure Dart with no dependencies, and the core library runs on every platform, including the web.
How to use it
Add it from GitHub:
dependencies: throttled_location: git: https://github.com/AbdeldjalilChougui/throttled_location Then build a reporter from a source, a sink and two policies:
import 'package:throttled_location/io.dart'; import 'package:throttled_location/throttled_location.dart'; Future<ThrottledLocationReporter> startTracking({ required LocationSource source, // see the adapter below required Stream<bool> online, // e.g. from connectivity_plus required String backlogPath, // e.g. from path_provider required Future<Map<String, Object?>> Function(List<Map<String, Object?>>) postPoints, // your HTTP call }) async { final reporter = ThrottledLocationReporter( source: source, sink: LocationSink.fromFunction((batch) async { // Throwing (offline, timeout, 5xx) keeps the batch and retries. final body = await postPoints([for (final f in batch) f.toJson()]); final next = body['next_update_seconds']; return SinkResult.accepted( nextInterval: next is int ? Duration(seconds: next) : null, ); }), policy: const ReportingPolicy( minInterval: Duration(seconds: 5), maxInterval: Duration(minutes: 2), maxAccuracyMeters: 50, heartbeatInterval: Duration(minutes: 5), ), backlog: BacklogPolicy( maxCount: 500, maxAge: const Duration(hours: 1), overflow: BacklogOverflow.downsample(keepEvery: 2), ), store: JsonFileBacklogStore(backlogPath), connectivity: online, batchSize: 50, ); reporter.statsStream.listen((s) => print(s)); await reporter.start(); return reporter; } Call pause() when the courier goes off duty, resume() when they come back, and stop() when the job ends. stop() makes one last delivery attempt and then persists whatever is still queued.
The source is an adapter around your location plugin. With geolocator it looks like this:
final geolocatorSource = LocationSource.fromStream( () => Geolocator.getPositionStream( locationSettings: const LocationSettings( accuracy: LocationAccuracy.high, distanceFilter: 0, // the policy does the throttling ), ).map( (p) => LocationFix( lat: p.latitude, lon: p.longitude, accuracy: p.accuracy, // Platforms report -1 (or 0 on some devices) when unknown. speed: p.speed >= 0 ? p.speed : null, heading: p.heading >= 0 ? p.heading : null, altitude: p.altitude, timestamp: p.timestamp, isMocked: p.isMocked, ), ), ); Ask for location permission before calling start(). The package never asks for permissions. For plugins that only offer a one-shot "current position" call, wrap the call in PollingLocationSource(read, period: ...), and reads never overlap. The README also has an adapter for background_location_free, a sibling package that provides a foreground-service location stream on Android. This package does not depend on it.
How a fix is judged
The rules run in a fixed order:
- The mock filter, the accuracy filter, the out-of-order filter and the jitter filter. A fix that fails any of them is dropped.
- The first fix after
startorresumeis sent. - A fix less than
minIntervalafter the last send is skipped. - A fix that leaves the stationary radius is sent.
- While stationary, a fix is skipped unless a heartbeat is due.
- Once the interval (server override, else the speed band) has passed and the device has moved at least
minDistanceMeters, the fix is sent. - A course change of at least
turnDegrees, at a speed of at leastturnMinSpeedMps, is sent. - If a heartbeat is due, the fix is sent. Otherwise it is skipped.
A heartbeat timer also re-sends the last valid fix when the GPS goes quiet.
ReportingPolicyEngine is the synchronous core behind these rules. It does no I/O and starts no timers, so you can use it on its own, for example to thin a recorded track: engine.evaluate(fix, now) returns a SendDecision, a SkipDecision or a DropDecision.
Things to know
- It does not read the GPS or ask for permissions. You supply the
LocationSource. - Distances use a spherical Earth: the Haversine formula with the IUGG mean radius of 6 371 008.8 m. That is off by up to about 0.5% from the WGS-84 ellipsoid, which is well below GPS noise at the distances involved.
- Timestamps matter. Age limits and the stationary timer compare the fix's own
timestampwith the injected clock. A device with a badly wrong clock can expire points early or late. - The defaults are engineering defaults. The speed bands, the 30 m stationary radius and the 70 m/s jump limit were tuned on synthetic tracks. They are not values from a study. Tune them for your fleet.
-
JsonFileBacklogStorerewrites the whole file on every change. That is fine for a few thousand points. For more, implementBacklogStoreon a database. It needsdart:io, so it is not available on the web. -
stop()is final. Create a new reporter to track again.
Why I built it
The problem the README describes is a mismatch: the GPS gives one fix per second, and neither the battery, nor the data plan, nor the server wants one request per second. A fixed timer is the usual shortcut, and it is wrong in both directions. It sends too much while the courier is parked, and too little in a turn. And it does nothing for the tunnel.
I wanted the decision in one place, as rules that can be read and tested: an ordered list that says why each fix was sent, skipped or dropped. I also wanted it separate from the GPS plugin and the HTTP client, so the same policy works whatever the app uses to get positions or to post them, and so the whole thing runs under fake_async without a device.
Get the code
The source, the adapters and the tests are on GitHub: https://github.com/AbdeldjalilChougui/throttled_location. It is MIT licensed. Issues and pull requests are welcome.
Originally published at abdeldjalilchougui.biz.

