我正在开发一个小部件,以便将我网站上的一些数据显示给其他人。为此,我必须通过javascript createElement方法动态加载一些脚本文件。这是我的代码。
<script language="javascript" type="text/javascript">
var script = document.createElement('script');
script.onload = function() {
//initMap();
};
script.src = "http://maps.google.com/maps/api/js?sensor=false";
document.getElementsByTagName('head')[0].appendChild(script);
function initMap()
{
var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
var mapOptions = {
zoom: 12,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}; var map = new google.maps.Map(document.getElementById(“map_canvas”),mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title:"Hello World!"
});
}
$(document).ready(function(){
initMap();
});
</script>
此代码既不在script.onload函数中初始化map,也不在document.ready上初始化map。提前谢谢。
答案 0 :(得分:1)
我不知道为什么,但似乎谷歌地图api在动态加载时没有完全加载。 相反,您可以使用Google Loader https://developers.google.com/loader/ 这很好。
以下是您修改后的<script>
:
var script = document.createElement('script');
script.src = "https://raw.github.com/getify/LABjs/master/LAB.min.js";
script.onload = function() {
$LAB
.script('http://code.jquery.com/jquery-1.8.0.min.js')
// .script('...') // other scripts which DO NOT depend on maps API
// if script X depends on jquery for example, it must be loaded like this:
// .wait() // this makes sure scripts above (jquery) are loaded before continuing
// .script('X')
.script('https://www.google.com/jsapi')
.wait(function() {
// this is called after everything above is loaded
google.load("maps", "3",
{
"callback" : onMapsLoad, // called when maps api loaded
"other_params": "sensor=false"
});
});
};
document.getElementsByTagName('head')[0].appendChild(script);
function onMapsLoad() {
$LAB
// add here scripts which DEPEND on Maps API
.script('https://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobox/src/infobox.js')
.wait(
function() {
// called when all above is loaded
$(function() { // makes sure DOM is ready
initMap();
});
}
);
}
function initMap()
{
var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
var mapOptions = {
zoom: 12,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}; var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title:"Hello World!"
});
}