Day 4: Integrating GPS for Tracking Running Routes


#GPSTracking #FitnessApp #RunningRoutes

Welcome to Day 4! Today, you’ll integrate GPS tracking into your fitness app, allowing users to record and visualize their running or walking routes. GPS functionality is essential for tracking distances and enhancing user engagement through real-world activity mapping.


What You’ll Learn Today

  1. Integrate location tracking with React Native.
  2. Use GPS data to record and display routes.
  3. Visualize routes on a map using react-native-maps.

Step 1: Install Required Dependencies

1. Install React Native Geolocation

npm install @react-native-community/geolocation

2. Install React Native Maps

npm install react-native-maps
npx pod-install

Step 2: Configure Location Permissions

1. Android

  • Add the following permissions to android/app/src/main/AndroidManifest.xml:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

2. iOS

  • Add the following keys to your Info.plist:
<key>NSLocationWhenInUseUsageDescription</key> 
<string>We need your location to track your routes.</string> 
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key> 
<string>We need your location to track your routes.</string>

Step 3: Implement GPS Tracking

1. Create a Component for Tracking Routes

Create a new file GPSTracker.js:

import React, { useState, useEffect } from 'react';
import { View, Text, StyleSheet, PermissionsAndroid, Platform } from 'react-native';
import Geolocation from '@react-native-community/geolocation';
import MapView, { Polyline } from 'react-native-maps';

const GPSTracker = () => {
  const [route, setRoute] = useState([]);
  const [currentPosition, setCurrentPosition] = useState(null);

  useEffect(() => {
    const requestLocationPermission = async () => {
      if (Platform.OS === 'android') {
        const granted = await PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION
        );
        if (granted !== PermissionsAndroid.RESULTS.GRANTED) {
          console.error('Location permission denied');
          return;
        }
      }
      startTracking();
    };

    requestLocationPermission();
  }, []);

  const startTracking = () => {
    Geolocation.watchPosition(
      (position) => {
        const { latitude, longitude } = position.coords;
        const newPoint = { latitude, longitude };
        setCurrentPosition(newPoint);
        setRoute((prevRoute) => [...prevRoute, newPoint]);
      },
      (error) => console.error(error),
      { enableHighAccuracy: true, distanceFilter: 10 }
    );
  };

  return (
    <View style={styles.container}>
      <MapView
        style={styles.map}
        initialRegion={{
          latitude: currentPosition ? currentPosition.latitude : 37.78825,
          longitude: currentPosition ? currentPosition.longitude : -122.4324,
          latitudeDelta: 0.01,
          longitudeDelta: 0.01,
        }}
      >
        {route.length > 1 && <Polyline coordinates={route} strokeWidth={4} strokeColor="#4caf50" />}
      </MapView>
      <View style={styles.info}>
        <Text style={styles.text}>Tracking your route...</Text>
        <Text style={styles.text}>Points Recorded: {route.length}</Text>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  map: {
    flex: 1,
  },
  info: {
    padding: 10,
    backgroundColor: 'white',
    alignItems: 'center',
  },
  text: {
    fontSize: 16,
  },
});

export default GPSTracker;

Step 4: Update App.js

1. Integrate the GPSTracker Component

Update App.js to render the GPS tracker:

import React from 'react';
import GPSTracker from './GPSTracker';

const App = () => {
  return <GPSTracker />;
};

export default App;

Step 5: Test the GPS Tracking

  1. Run the app: npx react-native run-android npx react-native run-ios
  2. Simulate GPS Movement:
    • On Android, test on a physical device by walking or moving around.
    • On iOS Simulator, simulate movement:
      • In Xcode, go to Features > Location > Freeway Drive to simulate location changes.
  3. Verify the Route:
    • Ensure the app records and displays your route as a polyline on the map.
See also  Day 3: Building a UI for Daily Goals and Achievements

Step 6: Enhance the GPS Tracker

1. Display Distance

  • Add a function to calculate the total distance covered:
import haversine from 'haversine'; 

const calculateDistance = (route) => { 
  let totalDistance = 0; 

  for (let i = 1; i < route.length; i++) { 
      totalDistance += haversine(route[i - 1], route[i]); 
  } 

  return totalDistance.toFixed(2); // Return distance in kilometers 
}; 

<Text style={styles.text}>Distance: {calculateDistance(route)} km</Text>
  • Install the haversine package: npm install haversine

2. Add Pause/Resume Tracking

  • Use state to toggle tracking on and off:
const [isTracking, setIsTracking] = useState(true); 

const toggleTracking = () => { 
  if (isTracking) { 
    Geolocation.stopObserving(); 
  } 
  else { 
    startTracking(); 
  } 
  setIsTracking(!isTracking); 

}; 
<Button title={isTracking ? 'Pause' : 'Resume'} onPress={toggleTracking} />

SEO Optimization for This Tutorial

Keywords: GPS tracking React Native, track running routes app, fitness app GPS, React Native polyline map, real-time location tracking.

Meta Description: Learn how to integrate GPS tracking in your fitness app with React Native. Record and visualize running or walking routes on a map in real time.


Summary

Today, you integrated GPS tracking into your app, allowing users to record and visualize their running routes on a map. You also learned how to calculate distances and enhance the user experience with pause/resume functionality.

What’s Next: Tomorrow, you’ll create an activity feed to display recent workouts and runs.

Stay tuned for Day 5: Creating an Activity Feed.


Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.