我有一个模态内的地图,我试图根据一组点调用fitBounds。点的值会因数据库值而异,但为了简化起见,我设置了下面的值。
当地图放置在模态之外时,它可以正常工作。但是,一旦进入模态,fitBounds 调用总是缩小得太远。
我认为这可能与模态不可见有关,但我已将函数放在模态回调中,这似乎没有帮助。
该网站使用的是 Laravel 5.8.38。
我的页面内容:
<head>
<!-- CSS Includes - Bootstrap 4.4.1 -->
{{ Html::style('css/app.css') }}
</head>
<body>
<div class="content">
<button class="btn btn-primary" data-toggle="modal" data-target="#map_modal">View Map</button>
</div>
<div class="modal" id="map_modal" tabindex="-1" role="dialog">
<div class="modal-dialog modal-md modal-dialog-centered" role="document">
<div class="modal-content">
<div id="map" style="margin: 15px; height: 300px; width: 300px;"></div>
</div>
</div>
</div>
<!-- JavaScript Includes - jQuery 3.4.1 -->
{{ Html::script('js/app.js') }}
<script type="text/javascript">
var map;
$('#map_modal').on('show.bs.modal', function (e) {
showMap();
});
function showMap() {
// points a and b will vary depending on database values and which elements the user interacts with
var a = new google.maps.Marker({
position: new google.maps.LatLng(41.7760588,-74.2972913),
map: map,
label: "A"
});
var b = new google.maps.Marker({
position: new google.maps.LatLng(41.9350477,-74.024461),
map: map,
label: "A"
});
var bounds = new google.maps.LatLngBounds();
bounds.extend(a.getPosition());
bounds.extend(b.getPosition());
map.fitBounds(bounds);
}
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 41.798057, lng: -73.973488},
zoom: 8
});
}
</script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=[key]&callback=initMap" async defer></script>
</body>
更新:
$('#request_modal').on('show.bs.modal', function (e) {
showMap();
});
需要更改为
$('#request_modal').on('shown.bs.modal', function (e) {
showMap();
});