2014-03-19 42 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