How To Create Navigation Direction MAP Using MAPBOX In React JS


In this article, we will learn how to create a navigation direction map (route by route) using MAPBOX in React JS.

Mapbox supports maps and site services for a good sort of net, mobile, automotive, and diversion applications. Mapbox is used to create different types of maps.

Mapbox provides Services Like :

  1. Map Service
  2. Search Service
  3. Navigation Service
  4. Vision Service

How To Use Mapbox

First, create a Mapbox account and get an access token to build different types of maps here.

Create Navigation Direction Map

  • Calculate optimal driving, walking, and cycling.
  • Instructions turn-by-turn.

Install Package

  • npm i mapbox-gl
  • npm i @mapbox/mapbox-gl-directions

Let’s understand with the following example.

Open your project in visual studio code.

Create a DirectionMap component and paste the below code in it.

import React, { Component } from 'react'
import mapboxgl from 'mapbox-gl';
import MapboxDirections from '@mapbox/mapbox-gl-directions/dist/mapbox-gl-directions';
import '@mapbox/mapbox-gl-directions/dist/mapbox-gl-directions.css' // Updating node module will keep css up to date.
mapboxgl.accessToken = 'pk.eyJ1Ijoic2FnYXJyYW5hOTU2NyIsImEiOiJja3IzYWkyenUyamd2MnpxYWMxd3BpbHBuIn0.vI5JBPmtXFeGbM0yjJMFcg';
export default class DirectionMap extends Component {
    constructor(props) {
        this.state = {
            lng: -70.9,
            lat: 42.35,
            zoom: 9
        this.mapContainer = React.createRef();
    componentDidMount() {
        const { lng, lat, zoom } = this.state;
        const map = new mapboxgl.Map({
            container: this.mapContainer.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-right');
        map.on('move', () => {
                lng: map.getCenter().lng.toFixed(4),
                lat: map.getCenter().lat.toFixed(4),
                zoom: map.getZoom().toFixed(2)
    render() {
        const { lng, lat, zoom } = this.state;
        return (
                <div className="sidebar">
                    Longitude: {lng} | Latitude: {lat} | Zoom: {zoom}
                <div ref={this.mapContainer} className="map-container" />

Next, call the DirectionMap component from APP.Js.

import logo from './logo.svg';
import './App.css';
import DirectionMap from './DirectionMap';

function App() {
  return (
    <DirectionMap />
export default App;


If you have any questions or face any problems with this article, please let me know in the comments.

For new blogs check. here.

Thank You.

Submit a Comment

Your email address will not be published. Required fields are marked *


Select Categories