Let's learn

with Roihan Salsabila

Blog

Subscribe

๐Ÿ›ฐ๏ธ Real-Time Location Tracking in React Native Using Expo, Firebase, and Google Maps

Roihan portraitRoihan Salsabila

23 days ago


๐Ÿ›ฐ๏ธ Real-Time Location Tracking in React Native Using Expo, Firebase, and Google Maps

Tracking user location in real-time is a powerful feature for many mobile applications โ€” whether it's food delivery, ride-hailing, or in our case: a mobile barber app that shows the barber approaching the customer.

In this tutorial, Iโ€™ll walk you through how I built a real-time location tracking feature using:

  • React Native + Expo
  • Firebase Firestore
  • Google Maps & Distance Matrix API

Letโ€™s dive in! ๐Ÿง 


โœจ What Weโ€™re Building

Weโ€™ll build a Map Page that does the following:

โœ… Tracks the barberโ€™s location in real time
โœ… Updates the Firebase database with the latest location
โœ… Shows a route from barber to customer using Google Maps Directions
โœ… Automatically navigates back when the barber is near (within 30 meters)


๐Ÿ”ง Tools & Dependencies

Weโ€™ll use these tools:

javascript

npm install react-native-maps react-native-maps-directions expo-location
npm install @react-native-async-storage/async-storage
npm install firebase axios

๐Ÿ”‘ Donโ€™t forget to:

  • Set up Firebase Firestore with two collections: Barbers and CustomersGet
  • Google Maps API Key (with Distance Matrix and Directions API enabled)

๐Ÿ“ฒ Flowchart: What Happens Behind the Scenes

javascript

User opens MapTrackingPage
     โ†“
Request Location Permission
     โ†“
Fetch user destination from Firestore
     โ†“
Every 10 seconds:
   โ”œโ”€ Track barber location
   โ”œโ”€ Save to Firebase (Barbers/1)
   โ”œโ”€ Fetch user location
   โ”œโ”€ Call Distance Matrix API
   โ””โ”€ If distance < 30 meters โ†’ goBack()

๐Ÿง  The Core Code Explained

Hereโ€™s a breakdown of the main parts of the feature.


1. ๐ŸŽฏ State Initialization

javascript

const [barberLocation, setBarberLocation] = useState({
  latitude: 0,
  longitude: 0,
  latitudeDelta: 0.0922,
  longitudeDelta: 0.0421,
});

We define both barber and customer location with default regions.


2. ๐ŸŽ›๏ธ Request Location Permission

javascript

let { status } = await Location.requestForegroundPermissionsAsync();
if (status !== "granted") {
  throw new Error("Location permission denied");
}

We need permission before tracking the user.


3. ๐Ÿ›ฐ๏ธ Real-Time Location Tracking

Every 10 seconds, we:

  • Fetch the barber's live location
  • Update Firestore
  • Calculate the distance to the customer

javascript

await Location.watchPositionAsync(
  { enableHighAccuracy: true, timeInterval: 20 },
  async (location) => {
    const docRef = doc(db, "Barbers", "1");
    await updateDoc(docRef, {
      location: {
        latitude: location.coords.latitude,
        longitude: location.coords.longitude,
      },
    });
  }
);

4. ๐Ÿ“ Get Customer Location

From Customers/1, we fetch the customerโ€™s saved location:

javascript

const docRef = doc(db, "Customers", "1");
const docSnap = await getDoc(docRef);
setUserLocation({
  latitude: docSnap.data().location.latitude,
  longitude: docSnap.data().location.longitude,
});

5. ๐Ÿงฎ Distance Calculation

We use the Google Distance Matrix API to calculate the distance between barber and user:

javascript

const url = `https://maps.googleapis.com/maps/api/distancematrix/json?origins=${barberLat},${barberLong}&destinations=${userLat},${userLong}&key=${GOOGLE_MAPS_APIKEY}`;
const { data } = await axios.get(url);

const distance = parseFloat(data.rows[0].elements[0].distance.text) * 1000;
if (distance < 30) {
  navigation.goBack(); // Barber has arrived
}

6. ๐Ÿ—บ๏ธ Displaying Markers & Route

We use react-native-maps and MapViewDirections to show everything visually:

javascript

<MapView>
  <Marker coordinate={barberLocation} />
  <Marker coordinate={userLocation} />
  <MapViewDirections
    origin={barberLocation}
    destination={userLocation}
    apikey={GOOGLE_MAPS_APIKEY}
    strokeWidth={3}
    strokeColor="red"
  />
</MapView>

๐Ÿ›ก๏ธ Tips for Production

Before deploying, keep these in mind:

TaskStatus
Hide Google Maps API Key in .envโš ๏ธ
Use authenticated user ID (not hardcoded "Barbers/1") โš ๏ธ
Add Firestore security rules โœ…
Handle GPS denied / unavailable โœ…
Add loading & error states๐ŸŸก



๐Ÿ”š Conclusion

And thatโ€™s it! We now have a real-time tracking page that:

  • Tracks barber location
  • Shows live updates on the map
  • Notifies user when the barber is nearby

This feature adds a premium user experience to any location-based service.

Say hi pro.roihan@gmail.com

Built with Next.js, Tailwind and Vercel

ยฉ2025 All rights reserved.