I am trying to keep the state of the map, to not rerender/initialize the map every time user returns to the map page.
I tried with context where i skip map initialization when map object is not empty, but then im getting blank map.
useEffect(() => {
const initializeMap = () => {
const map = new mapboxgl.Map({
container: mapContainerRef.current,
style: "",
center: [lng, lat],
pitch: 59.49999999999986, // pitch in degrees
bearing: -136.86837902659892, // bearing in degrees
zoom: zoom,
});
map.on("load", () => {
setMap(map);
map.resize();
});
console.log("init");
};
if (!map) initializeMap(); }, [map]);
Is this possible? Help much appreciated
EDIT:
Found someone asking the same question: https://github.com/mapbox/mapbox-gl-js/issues/8687
Im still having trouble with the container ref, if anyone know how i can update container with preivious map container that would be helpful. I can get previous container by calling map.getContainer()
just have no idea how to set it.
replacing previous div with context map solves this for me:
map ? document.getElementById("map").replaceWith(map.getContainer()) : "";
// in return
<div id={"map-container"}>
<div
id={"map"}
className="map-container"
ref={(el) => (mapContainerRef.current = el)}
/>
Now the map does not reload when navigating between pages
Context implementation example from someone else: https://codesandbox.io/s/mapbox-react-popups-fd4d4?file=/src/components/Map.js