[英]How to add multiple Leaflet map on the same page?
我想在同一頁面上添加多個具有不同內容的 Leaflet map 但它給了我錯誤:
Map container is already initialized.
我在 useEffect 中初始化useEffect
:
useEffect(() => {
if (!map) {
const newMap = L.map("map", {
zoomControl: true,
minZoom: minZoom,
maxZoom: maxZoom,
maxBounds: latLngBounds,
attributionControl: false,
}).setView(latLngCenter, defaultZoom)
L.tileLayer("https://{s}.basemaps.cartocdn.com/dark_nolabels/{z}/{x}/{y}{r}.png").addTo(
newMap
)
setMap(newMap)
}
}, [map])
然后我返回一個帶有id=map
的 div。
我在const newMap
行收到錯誤。 我想我們不能在同一頁面上有 2 張內容不同的地圖嗎?
我想我們不能在同一頁面上有 2 張內容不同的地圖嗎?
可以,但請確保使用 2 個不同的容器。 而一個HTML id
應該只用一次,因為按id查詢只會查到第一個。
因此,如果您獲得另一個具有相同id
的 map 容器,則會出現錯誤消息。
通常的解決方法是傳遞給L.map()
工廠的不是容器id
值,而是容器本身(作為 HTMLElement)。
對於 React,您可以為此目的使用useRef
掛鈎。 這樣,你的 React 自定義組件將只初始化它自己的 map 容器,你可以根據需要用 map 實例化任意數量的組件:
function CustomMapComponent() {
const mapContainerRef = useRef(null)
const [map, setMap] = useState(null)
useEffect(() => {
if (mapContainerRef.current) {
const newMap = L.map(mapContainerRef.current, options)
setMap(newMap)
}
}, [])
return (
<div ref={mapContainerRef} />
)
}
由於您已標記您使用 reactjs。我建議使用 leaflet-react https://react-leaflet.js.org/然后您可以使用任意數量的地圖,因為您將地圖用作普通組件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.