Watching foreground location
You can request foreground location permission and render watched coordinates as a map marker, providing the position data the rider screen needs to report.
Learning outcomes
- Explain why foreground location permission belongs behind the rider's explicit Go online action.
- Use
watchPositionAsync()to receive location updates at a requested 4000 ms interval. - Manage location subscriptions when the rider goes offline or the screen unmounts.
- Convert device coordinates into the
{ lat, lng }payload expected by the Go API. - Render restaurant and rider markers on a map and animate rider movement on Android.
A rider accepting an order needs to report their position while delivering it. The customer needs to see that position on a map, alongside the restaurant's location. Your rider screen collects coordinates, the Go API distributes accepted updates, and the customer screen displays the latest position.
The important boundary is between collecting a device position and displaying it. The rider's phone needs location permission and a location subscription. The customer does not need access to the rider's device APIs. It receives coordinates through the backend's existing tracking flow.
Location permission
Request location permission when the rider explicitly switches their availability to online. Do not request it when the application launches or when a customer opens the home screen.
This is Foreground location permission. The operating system asks the user to allow location access while the application is in the foreground.
Expo provides this API through the expo-location package. Install the package using:
npx expo install expo-locationUse requestForegroundPermissionsAsync() to request permission:
import * as Location from "expo-location";
async function requestLocationPermission(): Promise<boolean> {
const { status } =
await Location.requestForegroundPermissionsAsync();
return status === "granted";
}The function returns true only when the operating system grants permission. A denied permission must not be treated as successful.
There are three cases to consider:
- Permission is granted. You can start watching the rider's position.
- Permission is denied. The rider cannot go online because location updates are required.
- Location services are disabled. Permission alone does not guarantee that the device can provide a position.
The operating system controls permission decisions. Do not assume that a previous permission request will always succeed.
Foreground permission also has a boundary. It allows location tracking while the application is in use. It does not guarantee continuous updates after the application is minimized or closed.
This week's implementation uses foreground tracking only. Background tracking introduces additional operating system restrictions, permissions and battery considerations. You do not need background location permission for the rider workflow in this module.
Watching device positions
A single location request gives you one position. A delivery application needs repeated positions because the rider moves while carrying an order.
Expo provides watchPositionAsync() for this purpose. The watchPositionAsync API registers a callback that receives successive location updates and returns a subscription that you can later remove.
const subscription =
await Location.watchPositionAsync(
{
accuracy: Location.Accuracy.Balanced,
timeInterval: 4000,
},
(location) => {
console.log(location.coords.latitude);
console.log(location.coords.longitude);
}
);The options control how location updates are requested.
accuracy determines the desired accuracy of the location measurement. Location.Accuracy.Balanced is a reasonable starting point for this exercise because the customer map does not require continuous high-precision GPS measurements.
timeInterval specifies the desired minimum interval between location updates, in milliseconds, on Android. Setting it to 4000 requests updates approximately every four seconds.
This interval is a request, not a guarantee that the operating system will deliver a callback at exactly four-second intervals. Device conditions and location provider behaviour can affect the actual frequency.
The callback receives a LocationObject. Its coords property contains the position and additional information.
| Field | Meaning |
|---|---|
latitude | North-south geographic coordinate |
longitude | East-west geographic coordinate |
accuracy | Estimated horizontal accuracy in meters |
speed | Estimated speed, when available |
heading | Estimated direction of travel, when available |
For this application, latitude and longitude are the coordinates you need to send to the backend.
Location payload conversion
The device and API use different field names for coordinates. Expo provides latitude and longitude, while the Go location endpoint expects lat and lng.
Convert the fields before sending a location update:
function locationBody(pos: {
coords: {
latitude: number;
longitude: number;
};
}) {
return {
lat: pos.coords.latitude,
lng: pos.coords.longitude,
};
}For a device position with latitude 28.4601 and longitude 77.0302, the resulting payload is:
{
"lat": 28.4601,
"lng": 77.0302
}Send this payload to the authenticated POST /v1/rider/location endpoint using the existing application API client.
The backend associates the coordinates with the authenticated rider identity. Never trust a rider ID supplied by the mobile client as proof of identity.
The server also controls the location update frequency. The rider's phone requests updates approximately every four seconds, while the backend independently limits accepted updates to one every two seconds per rider. Client-side timing is not a substitute for server-side enforcement.
Location subscription ownership
Starting a location watcher is only half the implementation. You must also stop it.
Every successful watchPositionAsync() call returns a LocationSubscription. Its remove() method unregisters the callback and stops that subscription from receiving further updates.
If you forget cleanup, a rider can navigate away from the screen while location updates continue. Multiple subscriptions can also send duplicate positions.
A React ref can retain the subscription between renders:
const subscription =
useRef<Location.LocationSubscription | null>(null);
const stopTracking = () => {
subscription.current?.remove();
subscription.current = null;
};The Go online action should request permission before creating the subscription.
const goOnline = async () => {
const granted = await requestLocationPermission();
if (!granted) return;
stopTracking();
subscription.current =
await Location.watchPositionAsync(
{ accuracy: Location.Accuracy.Balanced, timeInterval: 4000 },
(location) => {
sendLocation(locationBody(location));
}
);
setIsOnline(true);
};The example separates permission handling from subscription creation. The location callback converts each position before sending it.
Going offline releases the subscription:
const goOffline = () => {
stopTracking();
setIsOnline(false);
};The rider screen also needs to remove the subscription when it unmounts. A cleanup effect provides the basic guarantee:
useEffect(() => {
return () => {
subscription.current?.remove();
subscription.current = null;
};
}, []);The cleanup runs when the component unmounts. The subscription should have one owner, the rider tracking screen.
There is an additional lifecycle detail. React components can unmount while asynchronous operations are still running. A permission request or watchPositionAsync() call might complete after the user has navigated away.
In a complete implementation, protect against this case. If watcher creation finishes after tracking has stopped or the screen has unmounted, remove the newly created subscription instead of retaining it. Also prevent rapid repeated Go online actions from creating overlapping subscriptions.
Map rendering
The customer needs to understand where the rider is geographically. Latitude and longitude values are useful for debugging, but customers need a map that provides spatial context.
Install React Native Maps:
npx expo install react-native-mapsThe library provides two important components:
MapViewrenders the map.Markerrepresents a geographic location on the map.
A map region contains four values:
| Field | Meaning |
|---|---|
latitude | Center latitude |
longitude | Center longitude |
latitudeDelta | Visible latitude span |
longitudeDelta | Visible longitude span |
For example, you can render a map around a location in Delhi:
import MapView, { Marker } from "react-native-maps";
<MapView
style={{ flex: 1 }}
initialRegion={{
latitude: 28.6139,
longitude: 77.2090,
latitudeDelta: 0.02,
longitudeDelta: 0.02,
}}
>
<Marker
coordinate={{
latitude: 28.6139,
longitude: 77.2090,
}}
/>
</MapView>The marker's coordinate property determines where it appears. The map's initialRegion property determines the initial visible area.
initialRegion does not continuously recenter the map whenever the rider moves. To change the visible area later, use the controlled region property or the map's animation methods.
The MapView and Marker concept is central to customer tracking. The customer needs a marker for the restaurant and another marker for the rider when a rider location becomes available.
These markers represent different locations and should remain separate. Do not use the rider's latest coordinates as the restaurant's position.
Marker rendering and performance
A map can contain several visual elements, including markers, custom marker images and overlays. Some marker content requires React Native to render a view into an image.
Continuously tracking complex marker views can create unnecessary rendering work. React Native Maps provides the tracksViewChanges property for this case.
<Marker
coordinate={riderCoordinate}
tracksViewChanges={false}
/>Setting this property to false tells the map not to continuously track changes to the marker's child view. This is useful when the marker contains static content, such as a rider icon.
There is an important distinction between changing a marker's geographic coordinate and changing its visual content.
A coordinate update should move the marker. A visual content update might require the marker view to be rendered again. Disabling view tracking does not disable coordinate updates.
For this application, use stable marker content. Avoid rebuilding marker views whenever a new location update arrives.
Animating the rider marker
Updating a marker's coordinate every four seconds can make the rider appear to jump between positions. Animation makes movement easier for the customer to follow.
React Native Maps exposes animateMarkerToCoordinate() on the marker instance for Android. A ref provides access to the rendered marker.
import { useEffect, useRef } from "react";
import { Marker } from "react-native-maps";
const markerRef = useRef<Marker>(null);
useEffect(() => {
markerRef.current?.animateMarkerToCoordinate(
riderCoordinate,
1000
);
}, [riderCoordinate]);The method receives a destination coordinate and an optional animation duration in milliseconds. A duration of 1000 requests a one-second transition to the new position.
The key detail is that you animate the existing marker. You do not need to recreate the entire map whenever the rider sends another location update.
On iOS, use an AnimatedRegion with the marker's animated coordinate and its timing method.
import { Platform } from "react-native";
import MapView, {
Marker,
AnimatedRegion,
} from "react-native-maps";
const markerRef = useRef<Marker>(null);
const animatedCoordinate = useRef(
new AnimatedRegion(initialCoordinate)
).current;The animated coordinate is initialized once and retained across renders.
When a new position arrives, use the appropriate platform animation:
useEffect(() => {
if (Platform.OS === "android") {
markerRef.current?.animateMarkerToCoordinate(
riderCoordinate,
1000
);
} else {
animatedCoordinate.timing(riderCoordinate).start();
}
}, [riderCoordinate]);The Android branch animates the existing marker. The iOS branch updates the animated coordinate.
The marker can use the animated coordinate:
<Marker.Animated
ref={markerRef}
coordinate={animatedCoordinate}
tracksViewChanges={false}
/>In a complete implementation, ensure the marker is mounted before attempting to animate it. Also consider how overlapping animations behave when a new location update arrives before the previous animation finishes.
Maps configuration in Expo
React Native Maps uses native platform functionality. Expo integrates the package when you install a compatible version through npx expo install.
For this exercise, use the default Maps configuration supported by Expo Go. You do not need to introduce a custom Google Maps API key.
A custom Google Maps key involves native application configuration. When you need custom Android Maps configuration for a standalone application, put the key in the Expo app configuration and rebuild the native application using a development build.
Expo Go is a prebuilt native application. It contains a fixed collection of native modules and configuration. Changing your project's app configuration does not automatically rebuild the Expo Go application.
The development workflow is:
- Install both packages using
npx expo install. - Start the application with Expo Go.
- Test the permission request on a physical device.
- Verify that the map renders.
- Verify that location updates move the rider marker.
A simulator can help you test map rendering. A physical device provides a more realistic test of location permissions, GPS behaviour and battery usage.
Rider tracking integration
The rider and customer screens have different responsibilities.
The rider screen requests foreground permission when the rider goes online. It starts a location watcher and sends coordinates to the backend approximately every four seconds. Going offline removes the subscription.
The backend authenticates the rider and accepts location updates through POST /v1/rider/location. It maintains the rider's Redis GEO position and controls how frequently updates are accepted.
When the order is picked up, the backend publishes accepted coordinates through the order's location channel. The customer receives those coordinates through the existing WebSocket tracking connection.
The customer screen updates its local rider coordinate state and moves the rider marker. It also maintains a separate restaurant marker and updates the order status timeline from incoming order events.
This separation matters because the customer should not need direct access to the rider's device location APIs. It receives location information through the backend's authorized tracking flow.
A location update is also not proof that the rider is still online. The backend maintains its own rider availability and position freshness rules. A customer should not treat an old coordinate as a live position indefinitely.
The existing order tab uses Polling every 10 seconds. That mechanism is useful for refreshing the order list, but live tracking uses the socket stream to deliver immediate updates rather than waiting for the next polling interval.
The Rider mode and customer tracking screens exercise connects these pieces. Keep the location subscription owned by the rider screen, convert coordinates at the API boundary, and let the customer map display the location received from the backend. The implementation must also preserve the existing order types and status model instead of maintaining a second version of order state.
Check your understanding
When should the rider application request foreground location permission?
References
Everything above is explained on this page; these are where it comes from.