我正在尝试通过显示正在添加的标记在谷歌地图中实现一些“强制动画”。
为此,我使用了以下代码。
function Marker(i) {
if(i > locations.length) return;
var populationOptions = {
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map,
center: citymap[locations[i][1]].center,
radius: citymap[locations[i][1]].population
};
cityCircle = new google.maps.Circle(populationOptions);
var t = setTimeout("Marker("+(i+1)+")",2000);
}
Marker(0);
这个例子来自:Here , 但 Firebug 说函数 Marker 没有在 setTimeout(); 的行上定义;
有什么想法吗?
更新代码:
function Marker(city) {
alert(city);
var populationOptions = {
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map,
center: citymap[city].center,
radius: citymap[city].population
};
cityCircle = new google.maps.Circle(populationOptions);
}
for (city in citymap) {
var t = setTimeout(function(){Marker(city);},2000);
}
我假设每次调用Marker都会有2秒的延迟,但事实并非如此。它等待 2 秒,然后一次运行 for all。 “城市”也不会更新,添加相同的标记 x 乘以城市 map 中城市的数量。
for循环不等待超时完成?
最佳答案
如果您希望每 2 秒添加一个新城市,并且即使在处理完 citymap 中的所有项目后也不会重复调用您的标记函数,您可以执行以下操作(同时摆脱全局计数器变量)
function Marker(count) {
city = Object.keys(citymap)[count];
console.log(city);
var populationOptions = {
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map,
center: citymap[city].center,
radius: citymap[city].population
};
cityCircle = new google.maps.Circle(populationOptions);
count++;
if(count<citymap.length){
setTimeout(function(){Marker(count);},2000);
}
}
Marker(0);
关于javascript - 每次添加标记时设置超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16437073/