在 Firebase 上部署的问题:Mapbox 保持灰色不加载

Problem with Deployment on Firebase: Mapbox remains gray dont load

我刚刚在线部署了我的 ReactJs 应用程序,我意识到 Map-box 在产品中不起作用,但它在本地主机中有效,首先我以为是产品环境中缺少令牌,添加它后地图仍然是灰色的.

我把我的地图的代码放在下面,希望它能帮助你,如果有人遇到同样的问题

import mapboxgl from 'mapbox-gl';
import useSWR from 'swr';
import lookup from 'country-code-lookup';
import './Map.css'
import 'mapbox-gl/dist/mapbox-gl.css';

mapboxgl.accessToken = `${process.env.REACT_APP_API_KEY_MAPBOX}`;

function Map({center, zoom}){
  const mapboxElRef = useRef(null); // DOM element to render map

  const fetcher = (url) =>
    fetch(url)
      .then((r) => r.json())
      .then((data) =>
        data.map((point, index) => ({
          type: 'Feature',
          geometry: {
            type: 'Point',
            coordinates: [point.countryInfo.long, point.countryInfo.lat]
          },
          properties: {
            id: index,
            country: point.country,
            cases: point.cases,
            deaths: point.deaths
          }
        }))
      );

  const { data } = useSWR('https://disease.sh/v3/covid-19/countries', fetcher);

  // Initialize our map
  useEffect(() => {
    if (data) {
      const map = new mapboxgl.Map({
        container: mapboxElRef.current,
        style: 'mapbox://styles/notalemesa/ck8dqwdum09ju1ioj65e3ql3k',
        center: center,
        zoom: zoom, // initial zoom
      });

      // Add navigation controls to the top right of the canvas
      map.addControl(new mapboxgl.NavigationControl());

      map.once('load', function () {
        // Add our SOURCE
        map.addSource('points', {
          type: 'geojson',
          data: {
            type: 'FeatureCollection',
            features: data
          }
        });

        // Add our layer
        map.addLayer({
          id: 'circles',
          source: 'points', // this should be the id of source
          type: 'circle',
          paint: {
            'circle-opacity': 0.75,
            'circle-stroke-width': ['interpolate', ['linear'], ['get', 'cases'], 1, 1, 100000, 1.75],
            'circle-radius': [
              'interpolate',
              ['linear'],
              ['get', 'cases'],
              1,
              4,
              1000,
              8,
              4000,
              10,
              8000,
              14,
              12000,
              18,
              100000,
              40
            ],
            'circle-color': [
              'interpolate',
              ['linear'],
              ['get', 'cases'],
              1,
              '#ffffb2',
              5000,
              '#fed976',
              10000,
              '#feb24c',
              25000,
              '#fd8d3c',
              50000,
              '#fc4e2a',
              75000,
              '#e31a1c',
              100000,
              '#b10026'
            ]
          }
        });

        const popup = new mapboxgl.Popup({
          closeButton: false,
          closeOnClick: false
        });

        let lastId;

        map.on('mousemove', 'circles', (e) => {
          const id = e.features[0].properties.id;

          if (id !== lastId) {
            lastId = id;
            const { cases, deaths, country} = e.features[0].properties;

            // Change the pointer type on mouseenter
            map.getCanvas().style.cursor = 'pointer';

            const coordinates = e.features[0].geometry.coordinates.slice();

            const countryISO = lookup.byCountry(country)?.iso2 || lookup.byInternet(country)?.iso2;
            const mortalityRate = ((deaths / cases) * 100).toFixed(2);
            const countryFlagHTML = Boolean(countryISO)
              ? `<img src="https://www.countryflags.io/${countryISO}/flat/64.png"></img>`
              : '';

            const HTML = `<p>Country: <b>${country}</b></p>
              
              <p>Cases: <b>${cases}</b></p>
              <p>Deaths: <b>${deaths}</b></p>
              <p>Mortality Rate: <b>${mortalityRate}%</b></p>
              ${countryFlagHTML}`;

            // Ensure that if the map is zoomed out such that multiple
            // copies of the feature are visible, the popup appears
            // over the copy being pointed to.
            while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {
              coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;
            }

            popup.setLngLat(coordinates).setHTML(HTML).addTo(map);
          }
        });

        map.on('mouseleave', 'circles', function () {
          lastId = undefined;
          map.getCanvas().style.cursor = '';
          popup.remove();
        });
      });
    }
  });
  return (
        <div className='map'>
            <div className='mapContainer'>
                <div className="mapBox" ref={mapboxElRef} />
            </div>
        </div>
    )
}

export default Map
`


  [1]: https://i.stack.imgur.com/vwD5j.png

好的,所以我自己找到了解决方案显然问题是最新版本的 mapBox,我解决了将 Mapbox-gl 版本降级到 1.13.0。这是解决问题之前的解决方法。

以下步骤:

  • 运行 yarn install 或者 npm install 或者
  • 运行 纱线 build 或 npm build

将此代码添加到您的地图渲染组件。这对我有用。

import mapboxgl from "mapbox-gl"; 

// eslint-disable-next-line import/no-webpack-loader-syntax
mapboxgl.workerClass = require("worker-loader!mapbox-gl/dist/mapbox-gl-csp-worker").default;