2014-03-19 43 views
1

開發加載谷歌地圖的phonegap應用程序。使用下面的兩個JavaScript的谷歌地圖。一個JavaScript從本地加載,而其他JavaScript從服務器加載。phonegap - 動態添加javascript

var script = document.createElement('script'); 
script.src = 'http://maps.google.com/maps/api/js?sensor=true'; 
script.type = 'text/javascript'; 
document.head.appendChild(script); 
script.onload = function() { 
    var script1 = document.createElement('script'); 
    script1.src = 'js/jquery.ui.map.js'; 
    script1.type = 'text/javascript'; 
    document.head.appendChild(script1); 
    script1.onload = function() { 
     alert(google.maps.LatLng); 
    } 
}; 

這兩個javascripts應該在加載html頁面後加載。嘗試下面的代碼,並提及各種博客,但它不起作用。

如果在html頁面的標題標記中寫入相同的腳本,那麼它工作的很完美。但在我的應用程序中,我需要它動態加載。

請幫助....

解決: var doc_write = document.write; // Remember original method; document.write = function(s) {$(s).appendTo('body')}; $.getScript(' http://maps.google.com/maps/api/js?sensor=true ').done(function() { $.getScript('js/jquery.ui.map.js').done(function() { document.write = doc_write; // Restore method setTimeout(function() { alert(google.maps.LatLng); },1000); }) .fail(function(jqxhr, settings, exception) { alert(exception); // this gets shown document.write = doc_write; // Restore method }); }).fail(function() { alert('failed to load google maps'); });

問題: 這需要一些時間來初始化。

+0

正如你已經標記了jQuery,你可以使用[$ .getScript()](https://api.jquery.com/jQuery.getScript/) – Satpal

+0

類似的問題,我面臨。我需要實施recaptcha在phonegap.but phonegap傳遞'file://'中的請求導致錯誤 –

+0

@Satpal還嘗試使用$ .getScript,但同樣的問題 –

回答

-1

不要做這樣

它加載到你的應用程序的頁腳部分

+2

如何在頁腳部分輕按按鈕事件?請提供更多信息 –

+0

在點擊按鈕之前加載它,稍後您可以修改地圖 – prady00

0

調用你的JavaScript函數後,設備準備的功能。因爲如果您通過Xcode使用手機間隙,設備準備就緒功能需要一段時間才能加載,並且您的腳本在它之前被調用。

+0

僅在設備準備就緒後纔會調用此方法。 –

+0

您也可以在延遲後調用您的功能。 – Chomu