按需异步加载谷歌地图

load google map Asynchronously on demand

本文关键字:谷歌地图 加载 异步      更新时间:2023-09-26

我在一个jQuery插件中为我的一个页面调用谷歌地图,但它没有在tabdiv中加载整个地图。我猜解决方案是Ajax。我在谷歌上试过,但似乎不起作用。

非常感谢。。。

function initializeMap(address) {
 var mapVar = {
    latitude: "",
    longitude: "",
    myLatlng: ""
 };
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address }, function (results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
        mapVar.latitude = results[0].geometry.location.lat();
        mapVar.longitude = results[0].geometry.location.lng();
        mapVar.myLatlng = new google.maps.LatLng(mapVar.latitude, mapVar.longitude);
        //-----define map options---//
        var mapOptions = {
            center: mapVar.myLatlng,
            zoom: 15,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
        var marker = new google.maps.Marker({
            position: mapVar.myLatlng,
            map: map,
            title: address
        });
    } //end if 
   });
}

html

   <div id="map_canvas" style="width:61.4em; height:400px;"></div>

css

 #map_canvas { 
 width:61.4em;
 height: 100%;
}

我发现这个问题的解决方案是在页面加载完成后,通过注入脚本标记来响应window.onload事件/函数调用,按需异步加载映射。因为我的地图显示在jquery选项卡中,所以我已经向选项卡注册了事件。所以当特定选项卡被点击时。。。document.ready中的map Load函数在插件中调用,然后初始化保存实际映射请求数据的函数。

jQuery插件

  $.fn.loadGoogleMap = function () {
    var script_tag = document.createElement('script');
    script_tag.type = 'text/javascript';
    script_tag.src = "https://maps.googleapis.com/maps/api/js?key=yourKey=false&callback=initializeMap"
    document.body.appendChild(script_tag);
}

function initializeMap() {
address = PropertyDetail.d_fullAddress;
var mapVar = {
    latitude: "",
    longitude: "",
    myLatlng: ""
};
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address }, function (results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
        mapVar.latitude = results[0].geometry.location.lat();
        mapVar.longitude = results[0].geometry.location.lng();
        mapVar.myLatlng = new google.maps.LatLng(mapVar.latitude, mapVar.longitude);
        //-----define map options---//
        var mapOptions = {
            center: mapVar.myLatlng,
            zoom: 15,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
        var marker = new google.maps.Marker({
            position: mapVar.myLatlng,
            map: map,
            title: address
        });
    } //end if 
  });
 }

在document.ready()中调用插件函数。。。

 $("#map_canvas_tab").on("click", function () {
      $(this).loadGoogleMap();
      window.onload = loadScript;
  });