Home > OS >  How to add multiple Leaflet map on the same page?
How to add multiple Leaflet map on the same page?

Time:12-02

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?

CodePudding user response:

if max exists remove it first

 if(map) map.remove();
 else (!map) {  

      const newMap = L.map("map", {
        zoomControl: true,
        minZoom: minZoom,
        maxZoom: maxZoom,
        maxBounds: latLngBounds,
        attributionControl: false,
      }).setView(latLngCenter, defaultZoom)

CodePudding user response:

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} />
  )
}
  • Related