首页 > 解决方案 > 无法使用 JSON 变量设置 React-Leafletlet Maps CRS

问题描述

我无法使用以下代码为 React-Leaflet 设置 crs:

import CONFIG from 'config/config.json';
.
.
.
.
<Map
   ref={(m) => { this.leafletMap = m; }}
   center={this.props.mapCenter}
   zoom={zoomLevel}
   crs={CRS.EPSG900913}       // This works
   crs={CONFIG.leafletMapCRS} // This doesn't
>

这是我的 config.json 文件

{
"leafletMapURL": "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
"leafletMapCRS": "CRS.EPSG900913"
}

LeafletMapURL 配置条目工作正常,但 LeafletMapCRS 由于某种原因不起作用。任何帮助表示赞赏。

标签: react-leaflet

解决方案


CRS是具有某些属性的对象。在你的config.json你正在把它变成一个字符串。因此,您需要做的是删除""然后从'leaflet'. 完成此操作后,您将看到您必须将文件设置为 a.js而不是.json能够导入CRS.

因此,您将拥有:

import { CRS } from "leaflet";

export const config = () => {
  return {
    leafletMapURL: "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
    leafletMapCRS: CRS.EPSG900913
  };
};

接着:

import { config } from "./config";
...

 function App() {
  const bounds = [[-26.5, -25], [1021.5, 1023]];
  const configs = config();

  return (
    <Map
      center={[0, 0]}
      zoom={0}
      style={{ height: "100vh" }}
      crs={configs.leafletMapCRS} // This works
    >
      <ImageOverlay
        url="https://leafletjs.com/examples/crs-simple/uqm_map_full.png"
        bounds={bounds}
      />
    </Map>
  );
}

最后但并非最不重要的是,您确定可以使用CRS.EPSG900913吗?因为这里描述了可用的参考系统,CRS.EPSG900913但不包括在内。

演示


推荐阅读