我正在尝试在我的html文件中加载map1()函数,但它没有加载
这是html。如果我把它放在一个html文件下它工作正常,但现在我有一个单独的html和js文件它将无法正常工作。
<html>
<head>
<script src="map.js"></script>
</head>
<body>
<div id="map">
</div>
<script>
map1();
</script>
</body >
js就是这个。
function map1() {
var locations = [
['Rye Hall', 53.384915, -6.598975 ],
['Auxilla',53.384168, -6.598228 ],
['Education House', 53.383348, -6.597810 ],
['Gym', 53.384759, -6.603737 ],
['Students Union', 53.383056, -6.603694 ],
['Callan Building',53.383156, -6.602664 ],
['The Pheonix', 53.384368, -6.603641 ],
['Engineering Building', 53.384437, -6.602444, ],
['John Hume Building',53.383976, -6.600213, 4],
['Arts block', 53.383739, -6.601444, 5],
['Iontas', 53.384510, -6.600624, 3],
['Science Building',53.383125, -6.600575 , 2],
['Eoals', 53.384616, -6.601662, 1]
];
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 16,
center: new google.maps.LatLng(53.381567, -6.599668),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
答案 0 :(得分:1)
您似乎在尚未完全加载时调用map1()
函数。如果您在调用map1
之前等待文档加载,则不应该这样做。
<html>
<head>
<script src="map.js"></script>
</head>
<body>
<div id="map">
</div>
<script>
window.onload = function() {
map1();
}
</script>
</body >
答案 1 :(得分:0)
问题是您是否在页面加载之前尝试获取html元素:
var map = new google.maps.Map(document.getElementById('map')
尝试在此代码中将整个函数包装在js文件中:
window.onload = function() {
function map1() { ... }
}
但如果将它分成较小的函数并且只在文档加载时设置你的vars,那就更好了。