简体   繁体   中英

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:

Map container is already initialized.

I'm initializing the map in a 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 .

I'm getting the error on line const newMap . I think we can't have 2 maps on the same page with different contents?

I think we can't have 2 maps on the same page with different contents?

You can , but make sure you use 2 different containers. And an HTML id should be used only once, because when querying by id, only the first one is found.

Hence the error message if you get another map container with the same id .

The usual workaround is to pass to the L.map() factory not the container id value, but the container itself (as an HTMLElement).

With React, you would use the useRef hook for this purpose. 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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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