简体   繁体   English

如何在同一个页面添加多个Leaflet map?

[英]How to add multiple Leaflet map on the same page?

I want to add multiple Leaflet map with different content on the same page but it gives me the error:我想在同一页面上添加多个具有不同内容的 Leaflet map 但它给了我错误:

Map container is already initialized.

I'm initializing the map in a useEffect :我在 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])

Then I'm returning a div with id=map .然后我返回一个带有id=map的 div。

I'm getting the error on line const newMap .我在const newMap行收到错误。 I think we can't have 2 maps on the same page with different contents?我想我们不能在同一页面上有 2 张内容不同的地图吗?

I think we can't have 2 maps on the same page with different contents?我想我们不能在同一页面上有 2 张内容不同的地图吗?

You can , but make sure you use 2 different containers.可以,但请确保使用 2 个不同的容器。 And an HTML id should be used only once, because when querying by id, only the first one is found.而一个HTML id应该只用一次,因为按id查询只会查到第一个。

Hence the error message if you get another map container with the same id .因此,如果您获得另一个具有相同id的 map 容器,则会出现错误消息。

The usual workaround is to pass to the L.map() factory not the container id value, but the container itself (as an HTMLElement).通常的解决方法是传递给L.map()工厂的不是容器id值,而是容器本身(作为 HTMLElement)。

With React, you would use the useRef hook for this purpose.对于 React,您可以为此目的使用useRef挂钩 That way, your React custom Component would initialize only its own map container, and you can instantiate as many Components with map as you wish:这样,你的 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} />
  )
}

Since you have tagged that you use reactjs. I would recommend to use leaflet-react https://react-leaflet.js.org/ Then you can use as many maps you want since you use the maps as normal components.由于您已标记您使用 reactjs。我建议使用 leaflet-react https://react-leaflet.js.org/然后您可以使用任意数量的地图,因为您将地图用作普通组件。

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

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