What is Mapbox?
Mapbox GL JS is a JavaScript library that uses WebGL to render interactive maps from vector tiles and Mapbox styles. A WebGL map brings the possibility to render vector tiles on the client side, this way we get all the data accessible on the browser and we can interact with pretty much everything on the map.
Step 1 - Create a MapBox account
If you don't already have a Mapbox account, sign up for one here.
In order to show maps from Mapbox you need to register on their website in order to retrieve an access token required by the map component, which will be used to identify you and start serving up map tiles. The service will be free until a certain level of traffic is exceeded.
Later we will use the dotenv package module to hide your environment variables (in this case, our Mapbox access token) and then we’ll put that in our .gitignore
file so that hackers can’t abuse our tokens.
Step 2 - Create Directory
Create a directory to initialize the map. Here, I'm using create-react-app to create a skeleton React project. The following code creates a new directory to store the app you're about to write, then cd
into the folder.
$ create-react-app my-react-map-project
or
$ npm init react-app my-react-map-project
$ cd my-react-map-project
It will create a directory called my-react-map-app
inside the current folder. Inside that directory, it will generate the initial project structure:
my-react-map-app ├── README.md ├── node_modules ├── package.json ├── .gitignore ├── public │ ├── favicon.ico │ ├── index.html │ └── manifest.json └── src ├── App.css ├── App.js ├── App.test.js ├── index.css ├── index.js ├── logo.svg └── serviceWorker.js
Inside the package.json
file, you will see several scripts have been provided that allows you to run several commands from Terminal:
yarn start. Starts the development server.
yarn build. Bundles the app into static files for production.
yarn test. Starts the test runner.
yarn eject. Removes this tool and copies build dependencies, configuration files and scripts into the app directory. Beware: If you do this, you can’t go back!
You will also see that several dependencies have been installed: react, react-dom and react-scripts. Use yarn start
to start a server that will serve the React application. This opens the app at http://localhost:3000
.
The browser should now display the words "Hello World!"
Now, modify the App Component to reflect the following changes in the return()
.
import React, { Component } from "react"; import "./style.css"; class App extends Component { render() { return ( <div className="App">Hello World</div> ) } } export default App;
Our environment is set up and now we're ready to develop our map component.