DEV Community

hmintoh
hmintoh

Posted on • Edited on

5 2

How to: Mapbox with React.js

Getting started

  • Generate a MapBox access token in your account page
  • Download the npm library using yarn add mapbox-gl
  • Include the css in the <head> of your index.html file:
<link href='https://api.mapbox.com/mapbox-gl-js/v1.10.1/mapbox-gl.css' rel='stylesheet' />
Enter fullscreen mode Exit fullscreen mode

Creating a map

Create a BaseMap component:

import React, { useEffect } from "react";
import mapboxgl from "mapbox-gl";
import "./BaseMap.scss";

const BaseMap = () => {
  mapboxgl.accessToken = MAPBOX_ACCESS_TOKEN;

  useEffect(() => {
    new mapboxgl.Map({
      container: "mapContainer",
      style: "mapbox://styles/mapbox/streets-v11",
      center: [-74.5, 40],
      zoom: 9,
    });
  }, []);

  return <div id="mapContainer" className="map"></div>;
};

export default BaseMap;
Enter fullscreen mode Exit fullscreen mode
  • container: The HTML element in which Mapbox GL JS will render the map, or the element's string id. The specified element must have no children.
  • style: choose from a pre-defined Mapbox style or create your own using Mapbox studio
  • center: refers to the starting position in [long,lat]
  • zoom: refers to the initial zoom level

Other option parameters for Map can be found here.

Next, add basic styles in BaseMap.scss:

.map {
  width: 100%;
  height: 100%;
}
Enter fullscreen mode Exit fullscreen mode

Finally, add BaseMap into your view e.g. HomePage.js

import React from "react";
import BaseMap from "~Components/BaseMap/BaseMap";

const HomePage = () => {
  return (
    <>
      <h1>My map</h1>
      <BaseMap />
    </>
  );
};

export default HomePage;
Enter fullscreen mode Exit fullscreen mode

Displaying markers and controls

Navigation

This adds a zoom buttons and a compass.

const nav = new mapboxgl.NavigationControl();
map.addControl(nav, "top-right");
Enter fullscreen mode Exit fullscreen mode

Marker

This adds a marker component.

const marker = new mapboxgl.Marker()
  .setLngLat([103.811279, 1.345399])
  .addTo(map);
Enter fullscreen mode Exit fullscreen mode

Geolocate

This locates the user on the map based on the browser's geolocation API.

const geolocate = new mapboxgl.GeolocateControl({
  positionOptions: {
    enableHighAccuracy: true
  },
  trackUserLocation: true
});

map.addControl(geolocate, "top-right")
Enter fullscreen mode Exit fullscreen mode

And there you have it! 🎉

screenshot of page

  • If you are interested in using Mapbox with Vue.js, I have written a similar tutorial here
  • Mapbox official documentation here

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (1)

Collapse
 
gautham495 profile image
Gautham Vijayan • Edited

Neatly explained! Can I get the source code in GitHub please.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️