react-map-gl <Map> is not fullscreen until resizing window
Asked Answered
C

2

4

I am using the ionic framework with React and trying to display a map via mapbox and react-map-gl.

It is working, but the map is only 100px * 100px or so until I resize the page. I have set the width and height css properties to 100vw and 100vh respectively like so:

  <Map
    style={{width: '100vw', height: '100vh'}}
    initialViewState={{
      longitude: -122.4,
      latitude: 37.8,
      zoom: 14
    }}
    mapStyle="mapbox://styles/mapbox/streets-v9"
  >
    <FullscreenControl />
  </Map>

What could cause it to not be 100 % width and height before resizing the page?

Chadburn answered 6/2, 2022 at 10:54 Comment(0)
S
4

I had the same issue and was able to resolve it with a call to map.resize() in the map component onRender(). Try this:

<Map
    style={{width: '100vw', height: '100vh'}}
    initialViewState={{
        longitude: -122.4,
        latitude: 37.8,
        zoom: 14,
    }}
    mapStyle="mapbox://styles/mapbox/streets-v9"
    onRender={(event) => event.target.resize()}
>
    <FullscreenControl />         
</Map>

event is a MapboxEvent

event.target is a MapboxMap

MapboxMap which is actually a mapboxgl.Map instance has a resize function that can be called.

See react-map-gl API docs: https://visgl.github.io/react-map-gl/docs/api-reference/map#onrender

Springy answered 14/7, 2022 at 17:35 Comment(0)
B
2

@bapin93's solution didn't work for me, since the map was hidden on page load, and I was showing & hiding the map based on a state showMap.

Here is my solution:

import { Map } from "react-map-gl";
import type { MapRef } from "react-map-gl";

const CustomMap = ({showMap) => {
  const mapRef = useRef<MapRef>(null);

  useEffect(() => {
    if (showMap && mapRef.current) {
      mapRef.current.resize();
    }
  }, [showMap]);

  return (
      <Map
        ref={mapRef}
      />
  );
};

Bluegreen answered 1/8, 2023 at 19:59 Comment(1)
This. In my case the map was inside a tab. No amount of resizing would work unless the map was actually visible on the page (even though the map tab was apparently rendering / logging to the console). I put activeTabIndex in the dependency array for the useEffect, and voila.Brahman

© 2022 - 2024 — McMap. All rights reserved.