在循环遍历Gmaps API上的标记时,setTimeout函数不起作用

时间:2015-08-14 00:30:26

标签: javascript google-maps google-maps-api-3 settimeout

我试图连续绘制50个标记,每个标记之间有2秒。第一个标记在GPS位置(x,y)绘制,然后两秒钟后,第二个标记在GPS位置(x + 0.0004,y)绘制并继续,直到在地图上创建第50个标记。

我已将标记构造函数放在setTimeout函数中。 setTimeout函数放在for循环中。然而,当我运行它时,循环瞬间穿过50个标记(即每个标记之间没有2秒延迟)。关于我哪里出错的任何建议?

var map;
var longi = 174.7660981;

function initialize(){

    var mapProp = {
        //map properties
    };

    //create map object
    map = new google.maps.Map(document.getElementById("googleMap"), mapProp);

    //loop through setTimeout/Marker constructor
    for(i = 0; i < 50; i++){
        window.setTimeout(function(){
            var marker = new google.maps.Marker({
                position: new google.maps.LatLng(-36.8606873, longi),
                map: map
            });
            longi += 0.0004;
        }, 2000);
    }
}

google.maps.event.addDomListener(window, "load", initialize);

1 个答案:

答案 0 :(得分:2)

setTimeout工作正常。您将所有标记延迟2秒(它们之间的延迟不是)。

var map;
var longi = 174.7660981;

function initialize(){

    var mapProp = {
        //map properties
    };

    //create map object
    map = new google.maps.Map(document.getElementById("googleMap"), mapProp);

    //loop through setTimeout/Marker constructor
    for(i = 0; i < 50; i++){
        window.setTimeout(function(){
            var marker = new google.maps.Marker({
                position: new google.maps.LatLng(-36.8606873, longi),
                map: map
            });
            longi += 0.0004;
        }, 2000*i);
    }
}

google.maps.event.addDomListener(window, "load", initialize);

&#13;
&#13;
var map;
var longi = 174.7660981;

function initialize(){

    var mapProp = {
        center: {lat:0, lng:0},
      zoom: 15
    };

    //create map object
    map = new google.maps.Map(document.getElementById("googleMap"), mapProp);

    //loop through setTimeout/Marker constructor
    for(i = 0; i < 50; i++){
        window.setTimeout(function(){
            var marker = new google.maps.Marker({
                position: new google.maps.LatLng(-36.8606873, longi),
                map: map
            });
            longi += 0.0004;
          map.setCenter(marker.getPosition());
        }, 2000*i);
    }
}

google.maps.event.addDomListener(window, "load", initialize);
&#13;
body, html, #googleMap {
  height: 100%;
  width: 100%;
  }
&#13;
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="googleMap"></div>
&#13;
&#13;
&#13;