javascript - 每次添加标记时设置超时

标签 javascript google-maps settimeout

我正在尝试通过显示正在添加的标记在谷歌地图中实现一些“强制动画”。

为此,我使用了以下代码。

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/

相关文章:

javascript canvas setTimeout 控制台 TypeError : is not a function

jquery - 如何在 Javascript 中检查变量是否超时?

android - 为什么我的网络浏览器上的谷歌地图不断加载? (德尔福 XE6 和安卓)

google-maps - Google Maps V3 - 航点 + 带有随机文本的信息窗口

javascript - Angular 用户界面选择 : Fetch data from remote service

JavaScript 只读问题

javascript - Google map API V3 英国地区

javascript - 为什么当我的站点打开多个选项卡时我的 setTimeout 会加快?

javascript - 将数组添加到哈希表

javascript - 如何在 Javascript SDK 中从 Deezer 队列中删除歌曲?