Live tracking looks simple in a demo. A driver’s position comes in and a marker moves on the map. On real roads it breaks in ways a demo never shows. GPS jumps a block away, the stream stops when the phone locks, the socket drops in a tunnel, and the car on the rider’s screen teleports instead of driving.
This guide builds the version that holds up on real rides. A driver app sends its location, a server relays it, and a rider app shows a marker that moves smoothly. It is based on what I worked on in SheDrives, a women-only ride-hailing app in Lahore with 10,000+ downloads, where live tracking was the hardest part of the app.
All the Dart code below is in one file and passes flutter analyze. The GPS filter has a unit test. Tested with Flutter 3.35, geolocator 14.0, google_maps_flutter 2.14 and web_socket_channel 3.0.
How the pieces fit
There are three parts:
- Driver app. It reads GPS with
geolocator, drops bad readings, and sends the latest good position every 4 seconds over a WebSocket. - Server. It keeps one “room” per trip, checks that the sender really is that trip’s driver, and passes each position to the rider in the same room.
- Rider app. It receives positions and animates the car marker from the old point to the new one, so the movement looks continuous.
Why a WebSocket and not a database write for every update? You can use Firestore or Supabase Realtime, and for small apps they’re fine. But at one update every 4 seconds, each active driver makes 900 writes an hour. A WebSocket server only passes messages along, so the cost stays flat as you grow. And you need the socket anyway if you have live features like driver bids.
From SheDrives: live tracking and driver bids first worked through polling, and both lagged. Moving them onto a WebSocket connection, and splitting connection handling, ride state and UI into separate layers, is what made them reliable. More on that in the SheDrives case study.
Step 1: Packages and platform setup
dependencies:
geolocator: ^14.0.2
google_maps_flutter: ^2.14.2
web_socket_channel: ^3.0.3
Android (android/app/src/main/AndroidManifest.xml): add these above <application>:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_LOCATION" />
Then add the Maps key inside <application>:
<meta-data android:name="com.google.android.geo.API_KEY"
android:value="YOUR_ANDROID_MAPS_KEY" />
iOS:
Info.plistneedsNSLocationWhenInUseUsageDescriptionandNSLocationAlwaysAndWhenInUseUsageDescription. Write a real sentence in each, such as “Your location is shared with your rider during a trip”, because App Review reads them.- For updates while the app is in the background, add
locationtoUIBackgroundModes. - Give the Maps SDK its key in
AppDelegate.swiftwithGMSServices.provideAPIKey("YOUR_IOS_MAPS_KEY").
Restrict both Maps keys in Google Cloud Console: the Android key to your package name and signing certificate, the iOS key to your bundle ID. A Maps key inside an app can be pulled out of the install file, so the restriction is what protects it. The same idea applies to any key, see keeping API keys out of your app.
Step 2: Ask for permission properly
Future<bool> ensureLocationPermission() async {
if (!await Geolocator.isLocationServiceEnabled()) {
await Geolocator.openLocationSettings();
return false;
}
var permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
}
if (permission == LocationPermission.deniedForever) {
await Geolocator.openAppSettings();
return false;
}
return permission == LocationPermission.always ||
permission == LocationPermission.whileInUse;
}
Ask at the moment it makes sense. For a driver, that is when they tap “Go online”, not on the first launch. A request that comes with a reason the user can see gets accepted far more often.
Step 3: Keep updates coming when the screen is off
A driver’s phone sits in a mount with the screen locked or another app open. By default, location updates stop when your app leaves the screen. Set this up per platform:
LocationSettings driverLocationSettings() {
if (defaultTargetPlatform == TargetPlatform.android) {
return AndroidSettings(
accuracy: LocationAccuracy.bestForNavigation,
distanceFilter: 5,
intervalDuration: const Duration(seconds: 2),
foregroundNotificationConfig: const ForegroundNotificationConfig(
notificationTitle: 'You are online',
notificationText: 'Sharing your location with your rider',
enableWakeLock: true,
),
);
}
if (defaultTargetPlatform == TargetPlatform.iOS) {
return AppleSettings(
accuracy: LocationAccuracy.bestForNavigation,
activityType: ActivityType.automotiveNavigation,
distanceFilter: 5,
pauseLocationUpdatesAutomatically: false,
allowBackgroundLocationUpdates: true,
showBackgroundLocationIndicator: true,
);
}
return const LocationSettings(accuracy: LocationAccuracy.high, distanceFilter: 5);
}
On Android, foregroundNotificationConfig starts a foreground service with a visible notification, so the system keeps your app alive.
- Start it while the app is on screen, when the driver taps “Go online”. Android then treats this as foreground location access.
- That way you usually don’t need
ACCESS_BACKGROUND_LOCATIONat all. That permission triggers an extra review in Google Play: a declaration form, a video and a prominent in-app disclosure. - Ask for it only if you must track with no notification showing, which a ride app rarely needs.
- Google Play also asks you to declare the foreground service type (location) in the Play Console when you target Android 14 or later.
On iOS, the blue location indicator in the status bar is the price of background updates. pauseLocationUpdatesAutomatically: false stops iOS from pausing updates when the car waits at a long red light.
Step 4: Throw away bad GPS readings
This is the part most tutorials skip, and it’s where real apps break. Phones report positions with an accuracy radius, and in cities, near tall buildings or in basements, a reading can be 100 m off, or jump across a block and back.
class FixFilter {
FixFilter({this.maxAccuracyMeters = 30, this.maxSpeedMps = 50});
final double maxAccuracyMeters;
final double maxSpeedMps; // 50 m/s = 180 km/h
Position? _last;
bool accept(Position p) {
if (p.accuracy > maxAccuracyMeters) return false;
final last = _last;
if (last != null) {
final meters = Geolocator.distanceBetween(
last.latitude, last.longitude, p.latitude, p.longitude);
final seconds =
p.timestamp.difference(last.timestamp).inMilliseconds / 1000;
if (seconds <= 0) return false;
if (meters / seconds > maxSpeedMps) return false;
}
_last = p;
return true;
}
}
Two rules do most of the work:
- Drop readings with a large accuracy radius.
- Drop readings that would mean the car moved faster than any car can.
The unit test for this feeds in normal city driving (accepted), an 80 m accuracy reading (rejected), a 1 km jump in 4 seconds (rejected) and a normal reading after it (accepted again).
From SheDrives: the most common real-device problem was inaccurate GPS. Positions on the map didn’t match where the driver really was. We moved to Google Maps Platform for more accurate location and tested repeatedly on real rides, not only in the emulator. Those test rides are where problems like this show up.
Step 5: Send the latest position every 4 seconds
Don’t send every reading. The GPS stream can fire every second, and most of those messages would be stale before the rider’s phone finishes drawing the last one. Keep the newest good position and send it on a timer:
class DriverLocationSender {
DriverLocationSender(this.socketUrl, this.tripId,
{this.every = const Duration(seconds: 4)});
final Uri socketUrl;
final String tripId;
final Duration every;
final _filter = FixFilter();
WebSocketChannel? _channel;
StreamSubscription<Position>? _gps;
Timer? _tick;
Timer? _retry;
Position? _latest;
int _attempt = 0;
bool _running = false;
Future<void> start() async {
if (!await ensureLocationPermission()) return;
_running = true;
await _connect();
_gps = Geolocator.getPositionStream(locationSettings: driverLocationSettings())
.where(_filter.accept)
.listen((p) => _latest = p);
_tick = Timer.periodic(every, (_) => _send());
}
Future<void> _connect() async {
try {
final channel = WebSocketChannel.connect(socketUrl);
await channel.ready;
_channel = channel;
_attempt = 0;
channel.stream.listen((_) {}, onDone: _reconnect, onError: (_) => _reconnect());
} catch (_) {
_reconnect();
}
}
void _reconnect() {
_channel = null;
if (!_running || (_retry?.isActive ?? false)) return;
final seconds = math.min(30, 1 << _attempt++); // 1, 2, 4 ... 30 s
_retry = Timer(Duration(seconds: seconds), _connect);
}
void _send() {
final p = _latest;
final channel = _channel;
if (p == null || channel == null) return;
channel.sink.add(jsonEncode({
'type': 'driver_location',
'trip': tripId,
'lat': p.latitude,
'lng': p.longitude,
'heading': p.heading,
'speed': p.speed,
'accuracy': p.accuracy,
'ts': p.timestamp.toUtc().toIso8601String(),
}));
}
Future<void> stop() async {
_running = false;
_tick?.cancel();
_retry?.cancel();
await _gps?.cancel();
await _channel?.sink.close();
}
}
How this holds up on the road:
- Why 4 seconds: in SheDrives we sent the driver’s location every 3 to 5 seconds. That kept the map smooth without flooding the connection. Each message is about 200 bytes, so that’s around 180 KB an hour per driver, which is nothing on mobile data.
- Reconnect with backoff: mobile connections drop all the time, in tunnels, lifts and network handovers. The sender waits 1, 2, 4, up to 30 seconds between attempts, so a dead server isn’t hit by every driver at once. When the socket comes back, the next tick sends the newest position, not a queue of old ones.
- The timestamp travels with the position, so the server and the rider can ignore anything that arrives out of order or too late to be useful.
The imports for this file are dart:async, dart:convert, dart:math (as math), package:flutter/foundation.dart, package:flutter/material.dart and the three packages.
Step 6: Move the marker smoothly on the rider’s map
If you set the marker to each new position, the car jumps every 4 seconds. Instead, animate it from where it is now to the new point over the same 4 seconds. The next update arrives just as the animation ends, so the car seems to drive continuously:
class DriverMap extends StatefulWidget {
const DriverMap({super.key, required this.updates, required this.start});
final Stream<Map<String, dynamic>> updates; // decoded socket messages
final LatLng start;
@override
State<DriverMap> createState() => _DriverMapState();
}
class _DriverMapState extends State<DriverMap> with SingleTickerProviderStateMixin {
late final AnimationController _anim =
AnimationController(vsync: this, duration: const Duration(seconds: 4));
late LatLng _from = widget.start;
late LatLng _to = widget.start;
double _heading = 0;
GoogleMapController? _map;
StreamSubscription<Map<String, dynamic>>? _sub;
@override
void initState() {
super.initState();
_anim.addListener(() => setState(() {}));
_sub = widget.updates.listen(_onUpdate);
}
void _onUpdate(Map<String, dynamic> m) {
if (m['type'] != 'driver_location') return;
final next = LatLng((m['lat'] as num).toDouble(), (m['lng'] as num).toDouble());
_from = _current; // start from wherever the marker is now
_to = next;
final heading = (m['heading'] as num?)?.toDouble() ?? -1;
final speed = (m['speed'] as num?)?.toDouble() ?? 0;
// Stopped cars report a heading of 0 or -1: keep the last good one.
if (heading >= 0 && speed > 1) _heading = heading;
_anim.forward(from: 0);
_map?.animateCamera(CameraUpdate.newLatLng(next));
}
LatLng get _current {
final t = Curves.linear.transform(_anim.value);
return LatLng(
_from.latitude + (_to.latitude - _from.latitude) * t,
_from.longitude + (_to.longitude - _from.longitude) * t,
);
}
@override
Widget build(BuildContext context) {
return GoogleMap(
initialCameraPosition: CameraPosition(target: widget.start, zoom: 16),
onMapCreated: (c) => _map = c,
markers: {
Marker(
markerId: const MarkerId('driver'),
position: _current,
rotation: _heading,
anchor: const Offset(0.5, 0.5),
flat: true,
),
},
);
}
@override
void dispose() {
_sub?.cancel();
_anim.dispose();
super.dispose();
}
}
// Turning raw socket messages into the stream DriverMap expects.
Stream<Map<String, dynamic>> decodeUpdates(WebSocketChannel channel) => channel.stream
.map((raw) => jsonDecode(raw as String))
.where((m) => m is Map<String, dynamic>)
.cast<Map<String, dynamic>>();
Some details here matter:
- Each animation starts from the current position, not the last target. If an update arrives early, the car doesn’t snap back first.
- Straight-line movement between two points is fine. Over 4 seconds of driving the error is a few metres. Snapping to roads is something the Roads API can do on the server if you need it.
flat: trueandrotationturn the car icon to the direction of travel and keep it flat on the map when the user tilts the camera. Use a top-down car image withBitmapDescriptor.assetfor the real app.- Heading is kept from the last moving reading. A stopped car often reports 0, which would spin the icon to face north at every red light.
The server: a relay with checks
The server can be small. Node.js, Go or Dart all work. What matters is what it checks:
- Only the trip’s driver can send positions to that trip. Authenticate the socket with the same token as your API, and check the trip ID against your database. Otherwise anyone who guesses a trip ID could move the car on a rider’s screen.
- Only the trip’s rider (and your support team) can receive them. Stop relaying when the trip ends.
- Store a thinned copy, not every message, for example one point every 30 seconds for receipts and disputes. Say so in your privacy policy, because location history is sensitive data, and both stores ask about it. The privacy policy generator and the Data safety helper cover location.
Testing it before real rides
- Android emulator: Extended controls → Location → Routes lets you play a route at different speeds.
- iOS Simulator: Features → Location → City Run or Freeway Drive gives a moving position.
- Real rides are the test that counts. Lock the screen, open another app, drive through an underpass, switch off mobile data for 20 seconds and turn it back on. Watch the rider’s map the whole time. The simulators never show you GPS drift near tall buildings.
Before you submit to the stores
- The permission text in
Info.plistmust explain why, in words a user understands. Vague text is a common reason for App Review questions. - If you do use
ACCESS_BACKGROUND_LOCATION, Google Play needs the location permissions declaration, a short video of the feature, and a prominent disclosure screen in the app before the permission prompt. - Fill in the location sections of the App Store privacy details and the Google Play Data safety form to match what you actually collect. The full checklist is in how to publish a Flutter app to the App Store and Google Play.
Frequently asked questions
How often should a driver app send its location?
Every 3 to 5 seconds is a good range for ride-hailing. Faster than that adds server load and battery drain, and the rider can’t see the difference because the marker is animated between updates anyway. Slower than about 10 seconds and the car visibly lags behind the real one when it turns.
Does Flutter location tracking work in the background?
Yes. On Android, use geolocator’s foreground notification setting, which runs a foreground service while the driver is online. On iOS, enable the location background mode and set allowBackgroundLocationUpdates. What you can’t do is keep tracking after the user force-closes the app, on either platform.
Should I use Firestore or a WebSocket for live tracking?
For a small number of drivers, Firestore or Supabase Realtime is quicker to set up. As you grow, every position becomes a billed write, around 900 an hour per active driver at a 4-second interval. A WebSocket relay costs the same however many messages pass through it, and you can use the same connection for bids and trip status.
Why does my marker jump or point the wrong way?
Jumping comes from setting the marker straight to each new position. Animate it between positions as in Step 6. A wrong direction comes from using the heading while the car is stopped, when phones report 0 or -1. Keep the last heading from a moving reading.
How much does a ride-hailing app with live tracking cost to build?
It depends mostly on the rider app, the driver app, the admin panel and the real-time backend. See how to build a women-only ride-sharing app for the full feature list, or get a quick estimate from the app cost calculator.
Building a ride-hailing, delivery or field-service app with live tracking? Tell me about it. I’m Muhammad Naeem, a Flutter developer in Lahore, and I have shipped live tracking in production. I’ll reply within 24 hours with questions and a rough plan.
Need a Flutter app built? Tell me about your project, or see case studies of apps I’ve worked on.