React Native Mobile App With Mapbox Navigation

by Editorial Team 47 views
Iklan Headers

Hey there, tech enthusiasts! Let's dive into creating a kick-ass React Native mobile app with Mapbox Navigation. This project, codenamed MOBILE-001, aims to integrate the Mapbox Navigation SDK to give users turn-by-turn navigation, along with other cool features. We'll be using React Native, which means we can build for both iOS and Android platforms from a single codebase. This is going to be epic!

Project Overview: The Road Ahead

This project is the final goal of Sprint 1. It directly addresses Known Issue #3: "No mobile app for CarPlay/Android Auto integration." Our goal is to build a mobile app that allows users to browse saved routes, view them on an interactive map, and then kick off turn-by-turn navigation. Plus, we're aiming to support CarPlay (for iOS users) and Android Auto, making the navigation experience even smoother. This is a big deal, and we're excited to share the journey.

Core Features

The app's primary functions include:

  • Browsing saved routes from our B-Road backend.
  • Displaying routes visually on an interactive map.
  • Starting turn-by-turn navigation using the Mapbox Navigation SDK.
  • Supporting CarPlay and Android Auto.

Tech Stack

Here's a sneak peek at the technology we're using:

  • Framework: React Native 0.73+ (This version is super stable and has lots of features.)
  • Maps: Mapbox Maps SDK for React Native (For those beautiful, interactive maps.)
  • Navigation: Mapbox Navigation SDK (The brains behind the turn-by-turn directions.)
  • State: Zustand (We're using Zustand to manage the app's state, keeping things organized and efficient.)
  • API Client: Axios (To communicate with our backend.)
  • CarPlay/AA: react-native-carplay / react-native-android-auto (For seamless integration with CarPlay and Android Auto.)

Project Structure: Where the Magic Happens

Let's take a look at the project structure to get a sense of how everything fits together.

mobile/
β”œβ”€β”€ android/
β”œβ”€β”€ ios/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ api/
β”‚   β”‚   └── client.ts          # Backend API client
β”‚   β”œβ”€β”€ components/
β”‚   β”‚   β”œβ”€β”€ Map.tsx            # Mapbox map component
β”‚   β”‚   β”œβ”€β”€ RouteList.tsx      # Route browser
β”‚   β”‚   β”œβ”€β”€ RouteDetail.tsx    # Route info + start nav
β”‚   β”‚   └── Navigation.tsx     # Turn-by-turn view
β”‚   β”œβ”€β”€ screens/
β”‚   β”‚   β”œβ”€β”€ HomeScreen.tsx
β”‚   β”‚   β”œβ”€β”€ BrowseScreen.tsx
β”‚   β”‚   β”œβ”€β”€ RouteScreen.tsx
β”‚   β”‚   └── NavigationScreen.tsx
β”‚   β”œβ”€β”€ store/
β”‚   β”‚   └── useAppStore.ts     # Zustand store
β”‚   β”œβ”€β”€ types/
β”‚   β”‚   └── index.ts           # TypeScript types
β”‚   └── App.tsx
β”œβ”€β”€ package.json
β”œβ”€β”€ tsconfig.json
└── README.md

Directory Breakdown

  • android/ & ios/: These directories contain the platform-specific code for Android and iOS, respectively.
  • src/: This is where all the app's source code lives.
    • api/: This folder houses the API client, which handles communication with the backend.
    • components/: Reusable UI components like the map, route list, and navigation interface will be stored here.
    • screens/: Each screen of the app (home, browse, route detail, navigation) has its own file here.
    • store/: The Zustand store will be managed here.
    • types/: Type definitions for TypeScript.
    • App.tsx: The main entry point of the application.
  • package.json: This file lists all the project's dependencies and scripts.
  • tsconfig.json: TypeScript configuration.
  • README.md: Project documentation.

Phase 1: Building the Basic App

1.1 Project Setup: Getting Started

First, we need to set up the React Native project. Here's how to do it:

npx react-native init BRoad --template react-native-template-typescript
cd BRoad
pm install @rnmapbox/maps zustand axios
  • npx react-native init BRoad --template react-native-template-typescript: This command creates a new React Native project named "BRoad" using the TypeScript template.
  • cd BRoad: Navigates into the project directory.
  • npm install @rnmapbox/maps zustand axios: Installs the necessary dependencies: the Mapbox Maps SDK, Zustand for state management, and Axios for API calls.

1.2 Core Screens: Laying the Foundation

Here are the core screens we'll be building in Phase 1:

  • Home Screen:

    • App branding.
    • A "Browse Routes" button to start exploring.
    • Quick access to recent routes.
  • Browse Screen:

    • Fetches routes from the /routes/public endpoint.
    • Displays routes in a list view with route cards (name, curvature, distance).
    • Includes pull-to-refresh functionality.
    • Allows searching/filtering by curvature score.
  • Route Detail Screen:

    • Displays a map preview with the route's polyline.
    • Shows route statistics (distance, curvature, segments).
    • Includes a "Start Navigation" button.
    • Provides an "Export GPX" option.

1.3 API Integration: Connecting to the Backend

We will need to connect our app to the backend API to fetch route data. Here's how the API client will be structured:

// src/api/client.ts
import axios from 'axios';

const API_BASE = 'https://api.b-road.app'; // Configure per environment

export const api = {
  getPublicRoutes: () => axios.get(`${API_BASE}/routes/public`),
  getRoute: (id: string) => axios.get(`${API_BASE}/routes/${id}`),
  getRouteGPX: (id: string) => axios.get(`${API_BASE}/routes/${id}/export/gpx`),
};

This code defines an api object with functions to interact with the backend API endpoints. It uses Axios to make HTTP requests and handles the base URL configuration.

Phase 2: Navigation - Taking it to the Next Level

2.1 Mapbox Navigation Integration

With our basic app in place, it's time to integrate the Mapbox Navigation SDK. Here's how we'll implement it:

import MapboxNavigation from '@rnmapbox/maps';

const startNavigation = (route: Route) => {
  // Convert route geometry to Mapbox directions format
  const waypoints = route.segments.map(seg => ({
    latitude: seg.start_lat,
    longitude: seg.start_lon,
  }));

  MapboxNavigation.startNavigation({
    origin: waypoints[0],
    destination: waypoints[waypoints.length - 1],
    waypoints: waypoints.slice(1, -1),
  });
};

This code snippet shows how to start navigation using the Mapbox Navigation SDK. It takes a Route object, converts its geometry to the format required by Mapbox, and calls MapboxNavigation.startNavigation() to initiate turn-by-turn directions.

2.2 CarPlay / Android Auto

Integrating CarPlay and Android Auto will significantly enhance the user experience. Here’s what we'll do:

  • iOS: We'll use react-native-carplay to create CarPlay templates, allowing users to view the route list and start navigation directly from their car's display.
  • Android: We'll use react-native-android-auto for Android Auto integration. This will allow for the same functionality as CarPlay.

Acceptance Criteria: Making Sure We're on Track

To ensure we're on track, here are the acceptance criteria for Phase 1:

  • React Native project initialized with TypeScript.
  • Mapbox Maps SDK integrated, with the map displaying correctly.
  • Home screen with navigation to the Browse screen.
  • Browse screen successfully fetching and displaying public routes.
  • Route detail screen with a map preview of the route.
  • Pull-to-refresh functionality implemented on the route list.
  • Basic error handling for any API failures.
  • iOS and Android builds that are working.
  • A comprehensive README file with setup instructions.

Environment Setup: Getting Your Development Environment Ready

iOS

  1. Navigate to the ios directory: cd ios
  2. Install iOS dependencies: pod install
  3. Add your Mapbox access token to the Info.plist file. This is crucial for the maps to work.

Android

  1. Open the android/app/build.gradle file.
  2. Add the Mapbox Maps SDK dependency: implementation 'com.mapbox.maps:android:10.x.x' (Replace 10.x.x with the latest version number).

Mapbox Token: The Key to the Maps

Set your Mapbox access token in a .env file at the root of your project:

# .env
MAPBOX_ACCESS_TOKEN=pk.xxx

Replace pk.xxx with your actual Mapbox access token.

Dependencies: The Tools of the Trade

Here's a list of the key dependencies we're using:

{
  "dependencies": {
    "@rnmapbox/maps": "^10.0.0",
    "axios": "^1.6.0",
    "zustand": "^4.4.0",
    "react-native-gesture-handler": "^2.14.0",
    "@react-navigation/native": "^6.1.0",
    "@react-navigation/stack": "^6.3.0"
  }
}

These dependencies provide the necessary tools for building the app.

References: For Further Exploration

That's it, folks! This is going to be an exciting project. We will keep you updated on the progress as we move forward. Stay tuned for more updates, and happy coding!