DEV Community

Cover image for Learn to Make a Location Tracking App file Using React and Mapbox
Johnny Santamaria
Johnny Santamaria

Posted on

Learn to Make a Location Tracking App file Using React and Mapbox

Easy guide to developing the map component in a React location tracking app

If you want to see yesterday's challenge: Building a leaderboard component

If you're going to try the challenge yourself: DailyUI

Overview

Today we will create a location tracking app using React and Mapbox. Our application will allow users to share their location with friends and track each other's movements in real time. We will build a user interface using React and utilize Mapbox, a mapping and location cloud platform, for the mapping and geolocation features.

What is Mapbox?

Mapbox is a powerful mapping and location cloud platform that offers a comprehensive suite of tools and services for building custom, interactive maps, location-based applications, and data visualizations. It is an open-source platform designed to be highly customizable and scalable, making it suitable for a wide range of industries, including transportation, logistics, real estate, and social networking.

now let’s get to building!

Prerequisites

Before getting started, make sure you have the following:

  • Node.js installed

    • Used to run Javascript everywhere
  • A Mapbox account and access token

  • Terminal to write commands

Setup

  1. Begin by creating a new React project using Create React App:
npx create-react-app location-tracker
cd location-tracker
Enter fullscreen mode Exit fullscreen mode

This command uses npx, a package runner tool that comes with Node.js, to execute the create-react-app command. This popular CLI tool generates a new React project with a default configuration and no build configuration required. In this case, location-tracker is the project name. The next line changes the directory to the location-tracker folder where the project will be.

  1. Install the required dependencies:
yarn add react-mapbox-gl mapbox-gl geolocation react-map-gl-geocoder
Enter fullscreen mode Exit fullscreen mode

This command installs the required dependencies for building a React application that uses Mapbox and geolocation features. Here's a brief explanation of each package:

  • react-mapbox-gl: A React binding library for Mapbox GL JS, which allows you to create interactive, customizable maps within your React application using WebGL

  • mapbox-gl: The core Mapbox GL JS library that provides the mapping functionality, including map rendering, interactive map controls, and support for various map sources and styles

  • geolocation: A package that enables you to retrieve the user's current geolocation coordinates (latitude and longitude) in the browser using the HTML5 Geolocation API

  • react-map-gl-geocoder: A React component that provides geocoding functionality for Mapbox GL JS maps. It allows you to convert addresses and place names into map coordinates and vice versa, enabling search and location input in your application

Implementing the Mapbox app

  1. Create a Map component in your src directory:
// components/Map.js

import React, { useRef, useEffect } from "react";
import MapGL from "react-mapbox-gl";
import { geolocate } from "geolocation";
import MapGlGeocoder from "react-map-gl-geocoder";

const Map = (
) => {
  const mapRef = useRef(null);
  const geocoderRef = useRef(null);

  useEffect(() => {
    const map = new MapGL(mapRef.current, {
      accessToken: "[your_mapbox_access_token]",
      style: "mapbox://styles/mapbox/streets-v11",
    });

    const geocoder = new MapGlGeocoder({
      map,
      accessToken: "[your_mapbox_access_token]",
    });

    geocoderRef.current = geocoder;

    // Geolocate user
geolocate().then(({ coords }) => {
      const { latitude, longitude } = coords;
      map.jumpTo({ center: [longitude, latitude], zoom: 15.5 });
    });

    // Cleanup
return () => {
      map.remove();
    };
  }, []);

  return (
    <>
      <MapGL
        ref={mapRef}
        width="100vw"
        height="100vh"
        onViewportChange={() => geocoderRef.current.update()}
      />
      <MapGlGeocoder ref={geocoderRef} />
    </>
  );
};

export default Map;
Enter fullscreen mode Exit fullscreen mode
  1. Update your App.js to include the Map component:
// App.js

import React from "react";
import Map from "./Map";

const App = (
) => {
  return (
    <div className="App">
      <Map />
    </div>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

Adding User Location Sharing and Tracking

  1. Implement a backend API for user authentication and sharing locations. This will require knowledge of backend development using a technology such as Node.js, Express.js, and MongoDB.

  2. Add user authentication to the React application using libraries like React Hooks for authentication.

  3. Implement features to share and track users' locations on the map by fetching user coordinates from the backend API.

Here is what the entire structure would look like in a repository

- public
  - index.html
- src
  - assets
    - logo.svg
    - images
  - components
    - Map.js
    - MapGeocoder.js
    - UserLocationMarker.js
    - LoginForm.js
    - RegistrationForm.js
    - UserProfile.js
  - pages
    - Home.js
    - Login.js
    - Register.js
    - UserProfile.js
  - styles
    - App.css
    - Map.css
  - index.js
  - App.js
  - setUpTests.js
- .gitignore
- package.json
- README.md
Enter fullscreen mode Exit fullscreen mode
  1. public: This folder contains the index.html file, which serves as the entry point of the application.

  2. src: The source code of your application resides here. It contains the following subfolders:

  • assets: Houses static files like images, logos, and icons.

  • components: Contains reusable UI components, including Map.js, MapGeocoder.js, UserLocationMarker.js, LoginForm.js, RegistrationForm.js, and UserProfile.js.

  • pages: Stores top-level React components, such as Home.js, Login.js, Register.js, and UserProfile.js.

  • styles: Contains CSS stylesheets for your components, like App.css and Map.css.

  1. Root Files: Inside the src folder, you'll find the following important files:
  • index.js: The entry point of your application, responsible for rendering the top-level App component.

  • App.js: The main component that serves as the container for your entire application.

  • setUpTests.js: A file for setting up testing environments, if needed.

  1. Root Files in Project Directory: The following files are located in the root directory:
  • .gitignore: A file specifying which files and directories should be ignored by Git.

  • package.json: The main project configuration file for Node.js and React applications, containing dependencies, scripts, and metadata.

  • README.md: A file providing general information, installation instructions, and usage details for your project.

Conclusion

In this tutorial, we learned how to create a basic location-tracking application using React and Mapbox. We implemented a map with geolocation capabilities, which is the foundation for user location sharing and tracking. To further enhance the app, consider adding features like search, user markers, and detailed user information. Happy coding!


Here you just saw only a few files made, here are some notes

Creating small files in software development, particularly in a React project, offers several benefits that can improve code maintainability, collaboration, and overall project organization. Here are some reasons why developers may choose to focus on small files:

  1. Modularity: Smaller files help promote modularity in code, making it easier to separate concerns, test, and reuse code. This approach also helps with the Single Responsibility Principle, which suggests that a module or function should have only one responsibility.

  2. Code Readability: Small files with a specific focus make the codebase more readable and easier to navigate, allowing developers to quickly understand the purpose of each file and its contents.

  3. Collaboration: In a team setting, smaller files simplify collaboration by enabling multiple developers to work on different components, services, or features simultaneously, with fewer merge conflicts.

  4. Performance: While modern development tools like Webpack and rollup.js can efficiently handle large files, splitting the code into smaller chunks can sometimes help with tree-shaking, lazy-loading, and improving initial load times, especially in browser-based applications.

  5. Debugging and Testing: It's easier to debug and test small, focused files compared to large monolithic files. Developers can pinpoint issues faster and ensure that each component or function works as expected, leading to better code quality and fewer bugs.

  6. Code Reusability: Small files with specific functionality can be easily reused across a project or even in other projects. This leads to a more maintainable and DRY (Don't Repeat Yourself) codebase.

In summary, focusing on creating small, modular files in a React project can enhance code organization, readability, and maintainability, and improve collaboration among team members.

Top comments (0)