在 bootstrap 模式中加载 google 动态纬度/经度地图

load google map on dynamic latitude / longitude in bootstrap modal

我遇到了 google 地图的问题。实际上我有一个列表页面,其中每一行都有地图按钮来显示特定行的 lat/long 的地图。

我正在使用 jQuery ajax 调用打开弹出窗口,其中 div

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
function showMap(id) {
   $("#map .modal-body").load("/showmap?id=" + id, function() { 
      $("#map").modal("show");
      return false; 
   });
}

虽然 showmap 模板有像

这样的地图显示代码
loadMap();

function loadMap() {

    var latitude = <?php echo $latitude ?>;
    var longitude = <?php echo $longitude ?>;

    map = new google.maps.Map(document.getElementById('map-body'), {
        zoom: 4,
        center: {lat: 21.0000, lng: 78.0000}
    });

    var myLatlng = new google.maps.LatLng(latitude, longitude);
    var marker = new google.maps.Marker({
            position: myLatlng,
            map: map,
            title: 'Location'
        });

    $('#map').on('shown.bs.modal', function () {
        var center = map.getCenter();
        google.maps.event.trigger(map, "resize");
        map.setCenter(center);
    });
}

工作正常。但是,为了减少主页加载时间,我需要在弹出窗口中包含地图脚本,这会产生问题,因为后续地图库未加载且代码出错。

我找到了从主页中删除包含的解决方案,并在弹出窗口中添加了以下代码,该代码定义了地图代码的回调(在所有库加载后延迟执行我的地图代码需要它)

$(document).ready(function() {
    $.getScript("https://maps.googleapis.com/maps/api/js?v=3.exp&callback=loadMap", function() {
        // No code here
     });
});

但后来我得到 google 映射多重包含错误。 "You have included the Google Maps API multiple times on this page. This may cause unexpected errors."

如果有人知道如何解决它?

看起来不存在真正的解决方案。但是我为此做了一个 hack。

首先我将代码移回我的视图文件并将回调设置为 cutom 函数而不是像

这样的映射函数
$(document).ready(function() {
    $.getScript("https://maps.googleapis.com/maps/api/js?v=3.exp&callback=checkLoading", function() {
        // No code here
    });
});
var mapEnabled = false;

function checkLoading {
    mapEnabled = true;
}

在地图加载功能中添加一个检查,仅当 mapEnabled 为真时才加载具有地图加载功能的弹出窗口 code/ui。

function loadMap(id) {
    if(mapEnabled == true) { 
        $("#map .modal-body").load("/showmap?id=" + id, function() { 
            $("#map").modal("show");
            return false; 
        });
    } else {
        $('.top-msg').html('<div class="alert alert-info alert-dismissible" role="alert"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>  Map is loading... Please wait and click again later.</div>');
    } 
}