[英]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.