我有一个全局变量map,在开始脚本标记之后声明 - 我还有一个全局变量test_var,在下面声明。在初始化函数中,我使用google maps api创建一个新的谷歌地图并将其分配给全局变量地图。在函数之外,我初始化地图并尝试console.log(map)和console.log(test_var)。前者返回undefined而后者返回42,但它们都是全局变量,所以我不明白为什么地图在初始化函数中赋值后,然后调用该初始化函数现在有一个未定义的值。
还有一件事:在控制台中,如果我尝试访问地图,或者像map.getBounds()这样的地图方法,它可以正常工作。问题是,为什么我不能以编程方式执行此操作,而不仅仅是在控制台窗口中。感谢
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Heatmaps</title>
<style>
//.......some styling.....//
</style>
<body>
/....some html..../
</body>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=visualization"></script>
<script>
var map;
test_var = 42;
var home = new google.maps.LatLng(50, -15) //map is centered somewhere in the atlantic ocean, change later
function initialize() {
var mapOptions = {
zoom: 3,
center: home,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
panControl: false,
zoomControl: true,
mapTypeControl: false,
scaleControl: false,
streetViewControl: false,
overviewMapControl: false
};
var styles = [
{
stylers: [
{ "gamma": 0.83 },
{ hue: "#00ffe6" },
{ saturation: -20 }
]
},{
featureType: "road",
elementType: "geometry",
stylers: [
{ lightness: 100 },
{ visibility: "simplified" }
]
},{
featureType: "road",
elementType: "labels",
stylers: [
{ visibility: "off" }
]
}
];
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
console.log(test_var); //this works!
console.log(map); //get undefined error, why?????
</script>
</head>
</html>
答案 0 :(得分:1)
这是因为在您调用initialize
时尚未调用事件处理程序(函数console.log(map)
)。尝试将console.log(map)
添加到按钮
<input type=button onclick="console.log(map)" value="Test map" />