In this article, we learn how to use Mapbox in React app.
First, Open our react project and install the mapbox-gl dependency.
npm i mapbox-gl
Then import the map and direction CSS into our file.
import 'mapbox-gl/dist/mapbox-gl.css'; import "@mapbox/mapbox-gl-directions/dist/mapbox-gl-directions.css";
Now import the map and map direction from mapbox-gl.
import mapboxgl from "mapbox-gl"; import MapboxDirections from "@mapbox/mapbox-gl-directions/dist/mapbox-gl-directions";
In the App.js file, we need to return div with the ref attribute and also we need longitude and latitude paramere by default to show one location on the map.
For the map, access needs an account in the mapbox and takes a token from there.
Now start to create the map, so that we need to pass the container, center, and style on the map.
map = new mapboxgl.Map({ container: mapContainerRef.current, style: "mapbox://styles/mapbox/streets-v11", center: [lng, lat], zoom: zoom });
For direction control pass token, unit, and profile in direction.
const directions = new MapboxDirections({ accessToken: mapboxgl.accessToken, unit: "metric", profile: "mapbox/driving", });
Now add mapbox and direction control to the map.
So, my App.js looks like this,
import React, { useRef, useEffect, useState } from "react"; import mapboxgl from "mapbox-gl"; import MapboxDirections from "@mapbox/mapbox-gl-directions/dist/mapbox-gl-directions"; import 'mapbox-gl/dist/mapbox-gl.css'; import "@mapbox/mapbox-gl-directions/dist/mapbox-gl-directions.css"; mapboxgl.accessToken = YOUR TOKEN; const App = () => { const mapContainerRef = useRef(null); const [lng, setLng] = useState(72.8311); const [lat, setLat] = useState(21.1702); const [zoom, setZoom] = useState(9); let map useEffect(() => { map = new mapboxgl.Map({ container: mapContainerRef.current, style: "mapbox://styles/mapbox/streets-v11", center: [lng, lat], zoom: zoom }); const directions = new MapboxDirections({ accessToken: mapboxgl.accessToken, unit: "metric", profile: "mapbox/driving", }); map.addControl(directions, "top-left"); map.addControl(new mapboxgl.NavigationControl()) return () => map.remove(); }, []); return <div className="map-container" ref={mapContainerRef} /> } export default App
Output:-