react-map-gl <Map> 在调整窗口大小之前不会全屏

问题描述 投票:0回答:2

我正在使用 React 的 ionic 框架,并尝试通过 mapbox 和 react-map-gl 显示地图。

它正在工作,但在我调整页面大小之前,地图只有 100px * 100px 左右。我已将宽度和高度 css 属性分别设置为 100vw 和 100vh,如下所示:

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

在调整页面大小之前,什么可能导致宽度和高度不是 100%?

reactjs ionic-framework mapbox react-map-gl
2个回答
3
投票

我遇到了同样的问题,并且能够通过调用地图组件 onRender() 中的 map.resize() 来解决它。试试这个:

<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
是一个 MapboxEvent

event.target
是一个 MapboxMap

MapboxMap 实际上是一个 mapboxgl.Map 实例,有一个可以调用的 resize 函数。

参见react-map-gl API文档:https://visgl.github.io/react-map-gl/docs/api-reference/map#onrender


0
投票

@bapin93 的解决方案对我不起作用,因为地图在页面加载时隐藏,并且我根据状态显示和隐藏地图

showMap

这是我的解决方案:

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}
      />
  );
};

© www.soinside.com 2019 - 2024. All rights reserved.