Mapbox GL Js, dynamically changing map container size, can not resize map
Asked Answered
C

1

7

My map instance lives in a resizable container, and when I change size I should call map.resize(). I was wondering is there a way to listen to mapbox container resize event so it can trigger map.resize() ? Can you advise how to do it?

export default function Map({ chartID, configuration, data }) {
  const classes = useStyles();
  const mapContainer = useRef(null);

  const [map, setMap] = useState(null);

  const [settings, setSettings] = useState({
    longitude: -73.935242,
    latitude: 40.73061,
    zoom: 9,
  });

  useEffect(() => {
    const geoFeatures = //...getting data

    const map = new mapboxgl.Map({
      container: mapContainer.current,
      style: 'mapbox://',
      center: [settings.longitude, settings.latitude],
      zoom: settings.zoom,
    });

    map.on('move', () => {...});

    //setting map to state if we need to reference it later
    setMap(map);
    // Clean up on unmount
    return () => map.remove();
  }, []);

  return (
    <div className={classes.mapWrapper}>
      <div ref={mapContainer} className={classes.map} />
    </div>
  );
}
Crandale answered 30/7, 2021 at 15:36 Comment(0)
C
12

I have ended up adding ResizeObserver and debounce map.resize()

   useEffect(()=>{
    //map init....
    const resizer = new ResizeObserver(_.debounce(() => map.resize(), 100));
    resizer.observe(mapWrapper.current); 

      return () => {
      resizer.disconnect();
      map.remove();
    };
},[])
Crandale answered 11/8, 2021 at 17:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.