mapbox.js在Bootstrap Modal中未完全渲染

5
我正在尝试使用mapbox.js制作经度和纬度选择器,并且需要将此地图放在模态框中,在单击“选择位置”按钮时打开。但是当这个模态框打开时,地图没有完全呈现。
这是我的代码:
<div class="modal fade" id="chooseLocation" tabindex="-1" role="dialog" aria-labelledby="chooseLocation" aria-hidden="true">
    <div class="Cadd-event-modal" style="width: 600px; margin: 0px auto; margin-top: 10%;">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
            <h4 class="modal-title Cfont-1">Choose location</h4>
        </div>
        <div class="modal-body" style="width: 500px; margin: 0px auto;">

            <div id='map'></div>
            <div class='map-overlay'>
                <label for='latitude'>latitude</label><br />
                <input type='text' size='5' id='latitude' /><br />
                <label for='longitude'>longitude</label><br />
                <input type='text' size='5' id='longitude' />
            </div>


        </div>
        <div class="model-footer"></div>
    </div>
</div>

脚本

    var map = L.mapbox.map('map', 'examples.map-9ijuk24y')
           .setView([0, 0], 2);

    // get the form inputs we want to update
    var latitude = document.getElementById('latitude');
    var longitude = document.getElementById('longitude');

    var marker = L.marker([0, 0], {
        draggable: true
    }).addTo(map);

    // every time the marker is dragged, update the form
    marker.on('dragend', ondragend);

    // set the initial values in the form
    ondragend();

    function ondragend() {
        var ll = marker.getLatLng();
        latitude.value = ll.lat;
        longitude.value = ll.lng;
    }

和按钮动作

$('#chooseLocation-btn').click(function(){
   $('#chooseLocation').modal('show');
});  
3个回答

10

我不确定你的问题是否已经解决了。然而,我也遇到了同样的问题,并通过使用以下代码来解决它。发布答案是因为它可能会帮助其他人。

$('#chooseLocation').on('shown.bs.modal', function () { // chooseLocation is the id of the modal.
    map.invalidateSize();
 });

嗨!谢谢你的回答。我不得不切换到谷歌地图,因为我的客户告诉我要使用谷歌地图,而且我也遇到了同样的问题。我记得在触发bootstrap事件时使用了resize(),所以...我认为在使用mapbox.js时也应该使用类似的东西。 - Arron
我也遇到了使用Bootstrap 3和Google Maps的选项卡相同的问题。这里是我的解决方案,这对我有效。不要再使用$('a[href="#Location"]').on('shown.bs.tab', function(e) {,而是使用$('#chooseLocation').on('shown.bs.modal', function () {来使其正常工作。不要忘记使用google.maps.visualRefresh = true; - Ravimallya

2

这里有一个使用Mapbox GL JS和map.resize()的好例子,用于制作选项卡。

$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
  var target = $(e.target).attr("href") // activated tab
  alert(target);
  map.resize();
});

0

备忘录:如果您的地图在隐藏的 div 中加载,而且 resize()invalidateSize() 都无法正常工作,请尝试在 map 元素上内联设置 overflow: visible

我正在一个 Bootstrap 模态框中加载地图,这意味着它在加载时是隐藏的。当地图在加载时被隐藏时,它无法找到其宽度或高度来定义地图元素的边界。设置 overflow: visible 似乎允许 resize() 函数执行。但这可能会导致布局问题,因为地图将延伸到地图元素的边界之外。您可以尝试将地图包装在另一个带有 overflow: hidden 的 div 中。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接