2013-01-18 111 views
1

我目前有一个页面显示结果的搜索。当用户点击结果时,详细信息使用ajax获取并加载到页面中。在这些细节中,有一个谷歌地图。异步显示多个谷歌地图

以前,我在细节页面中有回调的Gmaps脚本。但是我遇到了这个问题,即如果用户点击了几个结果,Gmaps脚本会被多次插入。

现在,我在结果页面中加载脚本,并在传递所有必要参数的同时详细信息页面调用初始化函数。但是我得到一个undefined is not a function错误。

所以我的问题是:如何构建Gmaps脚本,回调和两个页面(结果和细节)之间的映射的异步初始化?

结果页面

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&key=[key]"></script> 

function initialize(params) { 
var directionsService, directionsDisplay, map; 

directionsService = new google.maps.DirectionsService(); 
directionsDisplay = new google.maps.DirectionsRenderer(); 

// your typical gmaps stuff 

} 

详情页

<div id="map_canvas"></div> 

initialize(params); 
+0

可能重复[异步谷歌地图API V3不确定是不是一个函数(http://stackoverflow.com/questions/14184956/async-google-maps-api-v3- undefined-is-not-a-function) –

+0

加载一张地图不是问题(通过添加回调)。我不确定的是如何重复使用gmaps的'callback',而不会出现“您已经在此页面上多次包含Google Maps API”的错误。 – greener

+1

检查是否存在“google.maps”。当它存在时,只需调用初始化,如果没有,请使用加载器 –

回答

2

你能看到,如果谷歌地图的剧本已经通过检查该被添加了“谷歌”的全局变量已经加载到DOM。

Full jsfiddle example here: http://jsfiddle.net/gavinfoley/yD8Qt/

// dom ready 
 
    $(function() { 
 
     if (typeof google === "undefined") { 
 
      alert("Lazy loading Google maps"); 
 
      lazyLoadGoogleMaps(); 
 
     } else {     
 
      alert("Google Maps is already loaded"); 
 
      googleMapsLoaded(); 
 
     } 
 
    }); 
 

 
    function lazyLoadGoogleMaps() { 
 
     // Note the callback function name 
 
     $.getScript("http://maps.google.com/maps/api/js?sensor=true&callback=googleMapsLoaded") 
 
     .done(function (script, textStatus) {    
 
      alert("Google maps loaded successfully"); 
 
     }) 
 
     .fail(function (jqxhr, settings, ex) { 
 
      alert("Could not load Google Maps: ", ex); 
 
     }); 
 
    } 
 

 
    // This function name is passed in to the Google maps script load above 
 
    // and will be called once Google maps has loaded 
 
    function googleMapsLoaded() {   
 
     alert("Done!"); 
 
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

+0

由于DrMolle的评论,我设法解决它,但您的答案非常好。实际上,感谢您向我介绍'$ .getScript'。 – greener

+0

不用担心! '。.getScript'只是'.ajax'的简写包装,但是我喜欢它,因为它读取更好/更明显的你正在做的事情。 – GFoley83