繁体   English   中英

尝试加载 react-leaflet 时出错 map

[英]Getting error while trying to loading a react-leaflet map

我正在尝试加载 leaflet map 但它给了我一个错误:
Attempted import error: 'Map' is not exported from 'react-leaflet' (imported as 'LeafletMap').
我尝试再次安装 react-leaflet 并尝试在我的 App.js 文件中导入leaflet/dist/leaflet.css但它仍然向我显示错误。 这是代码
Map.js

import { Map as LeafletMap, TileLayer } from "react-leaflet";
import "./Map.css";

function Maps({ center, zoom }) {
  return (
    <div className="map">
      <LeafletMap center={center} zoom={zoom}>
        <TileLayer
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
          attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
        />
      </LeafletMap>
    </div>
  );
}

export default Maps;

应用程序.js

import './App.css'
import Maps from './Maps'
import 'leaflet/dist/leaflet.css'

function App() {
  const [mapCenter, setMapCenter] = useState({ lat: 34.80746, lng: -40.4796})
  const [mapZoom, setMapZoom] = useState(3)

return (
    <div className="app">
        <Maps
            center= {mapCenter}
            zoom= {mapZoom}
         />
    </div>
  )
}

export default App;

也许您没有使用正确版本的 react-leaflet(您的不导出地图)。 请参阅我的工作示例: https://codesandbox.io/s/react-leaflet-forked-mg8x4?file=/src/index.js 我用的是1.3.4

你没有你的 Map 的大小,也许问题出在这里

   <Map
       style={{ height: "100%", width: "100%" }}
       center={position}
       zoom={zoom}
   >

您错误地导入了组件。 如果您使用的是 react-leaflet 2.xx,则需要导入 Map,如下例所示。 如果你使用 react-leaflet 3.0.5,会有一些变化。 我用这个CodeSandBox中的最后一个 react-leaflet 做了一个例子。

Map.js

import { Map, TileLayer } from "react-leaflet";
import "leaflet/dist/leaflet.css";
import "./Map.css";

function Maps({ center, zoom }) {
  return (
    <div className="map">
      <Map center={center} zoom={zoom}
      {/* Give your map a size */}
      style={{ height: "100%", width: "100%" }}
        >
        <TileLayer
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
          attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
        />
      </Map>
    </div>
  );
}

export default Maps;

应用程序.js

import './App.css'
import Maps from './Maps'

function App() {
  const [mapCenter, setMapCenter] = useState({ lat: 34.80746, lng: -40.4796})
  const [mapZoom, setMapZoom] = useState(3)

return (
    <div className="app">
        <Maps
            center= {mapCenter}
            zoom= {mapZoom}
         />
    </div>
  )
}

export default App;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM