簡體   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