DEV Community

Cover image for Build a Location App with Mapbox and ReactJs (part one)
Jonathan Zihindula
Jonathan Zihindula

Posted on • Edited on

Build a Location App with Mapbox and ReactJs (part one)

Introduction

Hello !
Welcome to this tutorial which is the part one of the Mapbox integration in react app serie. In this serie we are going to build a location application using Mapbox and react as a framework. However in this tutorial we are going first to get the current location using mapbox.

Prerequis

To follow along this tutorial you must have a basic understanding of react . Don't worry about mapbox, I'm going to explain step by step , from the installation until integration. From this serie you can develop and integrate the location app using mapbox for large applications as you desire creating custum map design.

Tutorial Map

  • Create the react application
  • Install dependencies
  • Get Mapbox access token
  • Implement Mapbox and get the current location

Create React app

To create a react application open up to terminal and run the following code npx create-react-app locationapp.
Then cd locationApp to get into the locationapp folder.
The last code to run is code ., this commande is used to open the created app in the code editor.

Install dependencies

Let install Mapbox in our application by running npm install mapbox-gl or yarn add mapbox-gl.
Now our first and main dependencie installed , let get our access token .

Get mapbox access token

To use any of Mapbox's tools, we need a Mapbox access token. Mapbox uses access tokens to associate API requests with our account.
To create an access token go the mapbox official website , create an account then go to your profile dashbord , create an access token.

Note

This access token must be confidential , that why I can advice to always use it as an environment variable.

Mapbox implementation

In this part of tutorial we are going to jump into practice and get the map ready.
In your code editor create a file Mapbox.js and write the following code.

    import { useState, useEffect, useRef } from 'react';
    import mapboxgl from '!mapbox-gl';

    mapboxgl.accessToken = process.env.REACT_APP_MAPBOX_TOKEN;

    const Mapbox = ( ) => {

    const mapContainer = useRef(null);
    const map = useRef(null);
    const [lng, setLng] = useState(29.235600);
    const [lat, setLat] = useState(-1.683500);
    const  zoom = 13 ;

    useEffect(() => {
        if (map.current) return;

        //////////////// STORE THE MAP IN THE REF ////////////
        map.current = new mapboxgl.Map({
            container: mapContainer.current,
            style: "mapbox://styles/mapbox/streets-v11",
            center: [lng, lat],
            zoom: zoom
        });

       ///////////// CREATE GEOLOCATION CONTROL TO GET THE CURRENT LOCATION ///////
        const userLocation = new mapboxgl.GeolocateControl({
            positionOptions: {
                enableHighAccuracy: true
            },
            trackUserLocation: true,
            showUserHeading: true
        });

       /////////////////////// GET CURRENT LOCATION COORDINATES //////////////////////////////////
            userLocation.on('geolocate', (e) => {
            const lng = e.coords.longitude;
            const lat = e.coords.latitude
            const position = [lng, lat];
            setLat(lat);
            setLng(lng);
        });

     ///////////////////////// ADD THE USER LOCATION CONTROL ON THE MAP ///////////////////
      map.current.addControl(userLocation,"top-right");
    }, [lat,lng, zoom]);

    return  <div 
               ref={mapContainer} 
               style={{
                               position: "absolute",
                               top: 0,
                               left: 0,
                               bottom: 0,
                               height: "100vh",
                               width: "100%"
                           }} 
                  />
     }

    export deafult Mapbox;
Enter fullscreen mode Exit fullscreen mode

After import Mapbox.js file in App.js like this

  import Mapbox from './Mapbox';

     function App() {
        return (
             <div className="App">
               <Mapbox />
             </div>
         );
     }
    export default App;
Enter fullscreen mode Exit fullscreen mode

Now the application is ready to run , let do this by runnig in the terminal npm start.

Conlusion

Thank you for reading this first part of the serie, hope you enjoyed this and learned something from it.
For any feedback and question feel free to reach me out.
You can check out my portfolio as well.

Top comments (0)