【发布时间】:2012-05-13 01:55:46
【问题描述】:
在页面加载期间调用函数并向地图添加标记似乎真的很容易,但是我无法在页面加载时执行此操作,并且必须在地图加载后按下搜索按钮加载并准备就绪。我尝试使用此页面:
http://www.mkyong.com/javascript/javascript-call-funtion-after-page-load/
我在正文末尾放置了一个脚本来调用函数“addMarkers”,但没有任何反应。只有当我使用搜索按钮调用它时,我才能让这个函数正常工作。
地图自动加载后如何加载标记?
这是我的 html 正文:
<body>
<TR>
<TD>
<div id="map" style="width: 1250px; height: 750px"></div>
</TD>
<TD>
<!--field for start-->
<p>Start Date Time:</p>
<form method="post" action="">
<!--addMarkers button is called and executed correctly when this button is pressed-->
<input type="button" value="Search" onclick="addMarkers()">
</form>
</TD>
</TR>
<!--this does nothing or is not executed as I hoped-->
<script>
window.onload=addMarkers() ;
</script>
</body>
我的地图加载函数位于我的 html 文档的末尾:
<script type="text/javascript">
//***************Function moved out of header***************************************************
var map;
var markersArray = [];
var startformat;
var endformat;
function load() {
var myOptions = {
center: new google.maps.LatLng(42, -70),
zoom: 3,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"),myOptions);
alert("Click search to look for markers.");
}
load();
</script>
如果有什么我可以澄清的,请告诉我。
编辑: addMarkers() 使用显示的地图区域和来自两个文本字段的一些文本。就像人们一直在说的那样,似乎函数在一切准备就绪之前就被执行了。我需要先加载页面上的所有内容,然后以某种方式执行 addMarkers()...
这是我现在拥有的,但工作方式与以前相同。在我按下搜索按钮之前不会生成标记:
//************Part of head***************************************************
<script src="addcreateclear_Markers.js"></script>
<script type="text/javascript">
var map;
var markersArray = [];
var startformat;
var endformat;
function load() {
var myOptions = {
center: new google.maps.LatLng(42, -70),
zoom: 3,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"),myOptions);
addMarkers();
//alert("Click search to look for markers.");
}
</script>
</head>
<!--************Function in body***************************************************-->
<body onload='load()'>
<TABLE BORDER="0" CELLSPACING="0" CELLPADDING="2" ALIGN="Center" WIDTH=100%>
<TR>
<TD>
<div id="map" style="width: 1250px; height: 750px"></div>
</TD>
<TD>
<!--field for start-->
<p>Start Date Time:</p>
<form method="post" action="">
<input type="button" value="Search" onclick="addMarkers()">
</form>
</TD>
</TR>
</TABLE>
<script>
window.onload = addMarkers();
</script>
</body>
更多编辑: 在 html 正文的末尾调用此函数可以按我的意愿工作:
<script type="text/javascript">
function addMarkersLag() {
//Print the map object out to the console
console.log(map);
//Zoom in on the map after 2 seconds so you can see this function being called
window.setTimeout(function() {
addMarkers();
alert("Does it work?.");
}, 1000);
}
</script>
【问题讨论】:
-
在你
onload()你的地图标记之前,你应该先加载你的地图。注意顺序。 -
旁注:始终使用小写的标签。 (
<td>而不是<TD>) -
添加标记的代码在哪里?此外,您需要在加载地图后添加标记。
-
@Pete 添加标记的代码在头部。加载地图后如何添加标记?当我将加载脚本添加到标题时,它不起作用。
-
@Stagleton 你介意发布你所有的源代码吗?您确定您引用了 Google Maps API 吗?
标签: javascript html ajax google-maps-api-3