Search code examples
reactjsmapboxrendergithub-pagesmapbox-gl

Mapbox Map not displaying properly when deployed using Github Pages or Render, but works fine locally


I am trying to deploy a simple React app that has a map from Mapbox using Github Pages, but the map is not displaying properly. The coordinates and the zoom level on the sidebar seem to update as if the map was there; however, during deployment, the map grays out.

This is what it looks like when I test it locally using React:

enter image description here

This is what it looks like when it is deployed with Github Pages or Render:

enter image description here

Here's my code:

import React, { useRef, useEffect, useState } from 'react';
import mapboxgl from 'mapbox-gl';
import './Map.css';

mapboxgl.accessToken ='pk.eyJ1IjoiZi1hbHZhcmV6cGVuYXRlIiwiYSI6ImNsbTQ0eHp2YzNwb3czbW8yN3kyMTQwNXIifQ.i1tZc88cTP3Ci1-i0K7LCQ';

const Map = () => {
  const mapContainerRef = useRef(null);

  const [lng, setLng] = useState(5);
  const [lat, setLat] = useState(34);
  const [zoom, setZoom] = useState(1.5);

  // Initialize map when component mountsnp
  useEffect(() => {
    const map = new mapboxgl.Map({
      container: mapContainerRef.current,
      style: 'mapbox://styles/mapbox/streets-v11',
      center: [lng, lat],
      zoom: zoom
    });

    // Add navigation control (the +/- zoom buttons)
    map.addControl(new mapboxgl.NavigationControl(), 'top-right');

    map.on('move', () => {
      setLng(map.getCenter().lng.toFixed(4));
      setLat(map.getCenter().lat.toFixed(4));
      setZoom(map.getZoom().toFixed(2));
    });

    // Clean up on unmount
    return () => map.remove();
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

  return (
    <div>
      <div className='sidebarStyle'>
        <div>
          Longitude: {lng} | Latitude: {lat} | Zoom: {zoom}
        </div>
      </div>
      <div className='map-container' ref={mapContainerRef} />
    </div>
  );
};

export default Map;

This is the same code inside of the 'basic' directory in this Mapbox-React-Examples repository: https://github.com/mapbox/mapbox-react-examples

I haven't encountered this issue while running the application locally, and I am kind of lost. I initially tried to deploy the app using Render and had the same issue. I've also tried generating a new token and the issue persists.


Solution

  • Solved by changing the version of mapbox-gl inside of "package.json" to "mapbox-gl": "^2.15.0"