首页 > 解决方案 > 如何将 maplibre-gl 与 react-map-gl 一起使用

问题描述

我目前正在迈出使用maplibre和 react-map-gl 的第一步。

我已阅读有关如何使用 mapbox 的 fork 的文档

我已经适应了webpack-config。我使用带有rewind的create-react-app项目。这是我的 config-overrides.js。

module.exports = function override(config, env) {
    //do stuff with the webpack config...
    module.exports = {
        webpack: (config) => {
            config.module.rules.push({
                resolve:{
                    alias: {
                        ...config.resolve.alias,
                        'mapbox-gl': 'maplibre-gl'
                    }
                }
            })
          // Important: return the modified config
          return config
        },
      }
    return config;
  }

使用以下代码,我可以在几秒钟内看到 Maptiler 中的地图,该地图是通过 maplibre 加载的。

import React, { useState } from "react";
import ReactMapGL from "react-map-gl";

export const Map = () => {
  const [mapViewport, setMapViewport] = useState({
    height: "100vh",
    width: "100wh",
    longitude: 2.571606,
    latitude: 45.226913,
    zoom: 5
  });

  return (
    <ReactMapGL
      {...mapViewport}
      //mapboxApiAccessToken="MapboxToken"
      mapStyle= 'https://api.maptiler.com/maps/streets/style.json?key=MaptilerToken'
      onViewportChange={setMapViewport}
    ></ReactMapGL>
  );
};

然后它消失了,我在浏览器的控制台中看到了这个错误消息。

Error: A valid Mapbox access token is required to use Mapbox GL JS. To create an account or a new access token, visit https://account.mapbox.com/

如果我使用 line mapboxApiAccessToken="MapboxToken",我可以毫无问题地使用 maptiler 地图。

 import React, { useState } from "react";
import ReactMapGL from "react-map-gl";

export const Map = () => {
  const [mapViewport, setMapViewport] = useState({
    height: "100vh",
    width: "100wh",
    longitude: 2.571606,
    latitude: 45.226913,
    zoom: 5
  });

  return (
    <ReactMapGL
      {...mapViewport}
      mapboxApiAccessToken="MapboxToken"
      mapStyle= 'https://api.maptiler.com/maps/streets/style.json?key=MaptilerToken'
      onViewportChange={setMapViewport}
    ></ReactMapGL>
  );
};

但我不想再需要 mapbox 令牌了。我错过了什么?

我也在这里问过这个问题。

标签: webpackcreate-react-appreact-map-glmaplibre-gl

解决方案


覆盖是问题所在。config-overrides.js 应该是这样的

module.exports = function override(config, env) {
    config.module.rules.push({
        resolve:{
            alias: {
                ...config.resolve.alias,
                'mapbox-gl': 'maplibre-gl'
            }
        }
    })

    return config
}


推荐阅读