Mapbox-gl 高度 100%

Mapbox-gl height 100%

Mapbox 不适合它的容器。为什么不呢?

这是渲染后的 html:

<div class="map mapboxgl-map" id="mapBox">
  <div class="mapboxgl-canvas-container">
    <canvas class="mapboxgl-canvas" style="position: absolute; width: 1920px; height: 277px;" tabindex="0" aria-label="Map" width="1920" height="277">
    </canvas>
  </div>
</div>

那些 277px 我猜是默认值。

这是js:

mapboxgl.accessToken = 'blabla';
  var map = new mapboxgl.Map({
    container: 'mapBox',
    style: 'mapbox://styles/mapbox/streets-v11',
    center: [-77.04, 38.907],
    zoom: 11.15
  });

这是 scss:

.map {
  grid-column: 1/-1;
  height: 100%;
  position: relative;
  canvas, .mapboxgl-canvas {
    height: 100%;
  }
}

如果我将非常有名的 !important 添加到 height: 100%; 那么它可以工作但是地图被拉伸了。

我该怎么做?

我找到窍门了。

只需添加

map.on('load', function () {
    map.resize();
});

添加到 js,以便地图将根据其容器调整大小

将此添加到您的 css

.mapboxgl-map {
    position: absolute;
    top: 0;
    bottom: 0;
    width: 100%;
    }

{ position: relative } 到其父级 div

经过数小时的努力寻找解决方案并尝试解决方案,我终于明白了如何让 Mapbox 适合它的容器。要使 mapbox 适合它的容器,无需设置绝对高度,它必须是 parent div 的第一个 child。 Mapbox 不能是第二个、第三个或第四个 child 等。为什么?我的猜测是 mapbox-gl.css 与自定义 css 规则冲突。

每次都有效:

<section class="map_box_container">
    <!--MAP-->
  <div id='map'></div>
</section>

这永远行不通:

   <section class="map_box_container">
<div class="second_child">
        <!--MAP-->
      <div id='map'></div>
</div>
    </section>

CSS

.map_box_container{
  position: relative;
  height: 100% !important;
  width: 100% !important;
}

  #map {
    position: absolute;
    top: 0;
    bottom: 0;
    width: 100%;
  }

2021 年更新

我在一个新项目中使用 mapbox,我的理解是 mapbox 不需要它的 parent 容器有任何 css 工作。

HTML

<section class="map_box_container">
<!--MAP-->
<div id='map'></div>
</section>

CSS

#map {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
}

我发现的唯一可靠方法是使用 jQuery。在我的例子中,地图位于页面加载时未激活的选项卡中,因此我在切换到包含地图的选项卡时执行代码。

var $ = window["$"];
$('.mapboxgl-canvas').css('width', '100%');
$('.mapboxgl-canvas').css('height', '100%');

编辑:可行,但地图看起来丑陋且像素化。我可能会回到 Google 地图。

const [viewport, setViewport] = useState({ 宽度:'100%', height: 'calc(100vh - 162px)', // 162px是地图顶部所有元素的size高度 纬度:0, 经度:0, 缩放:12, 轴承:0, 间距:0, 过渡持续时间:2000, transitionInterpolator: new FlyToInterpolator(), });

这个对我有用。它需要一段时间才能生效,但它是值得的。

map.on('load', function() {
    $('.mapboxgl-canvas').css('width', '100%');
    $('.mapboxgl-canvas').css('height', '100%');
    map.resize();
});

没有绝对定位的纯 CSS 解决方案。

新方法:

添加到您的包装器:

aspect-ratio: 1 / 1;

如果您想要矩形(例如:.9),请使用该值。

旧方法:

每个 parent 的高度必须大于 0。请检查您的开发检查器。对于呈现高度为 0 的每个容器,添加 height: 100%;。然后为您的地图包装器添加这两个 CSS 声明:

height: 100%;
max-height: 500px;

将 500 更改为任何在您的媒体查询中有效的值,您应该会很好。