<script type="text/javascript">



$(document).ready(function () { initialize(); });

var markerarray = [
['Mount Evans', 39.58108, -105.63535, 4, 'This is Mount Evans.'],
['Badlands National Park', 43.785890, -101.90175, 1, 'This is Badlands National Park']
];


var bounds = new google.maps.LatLngBounds();

function setMarkers(map, markers) {

    for (var i = 0; i < markers.length; i++) {  setTimeout(function() {

        var markerarray = markers[i];

        var siteLatLng = new google.maps.LatLng(markerarray[1], markerarray[2]);

        var marker = new google.maps.Marker({

            position: siteLatLng,

            map: map,

            animation: google.maps.Animation.DROP,

            title: markerarray[0],

            zIndex: markerarray[3],

            html: markerarray[4]

        });


        google.maps.event.addListener(marker, "click", function () {

            $('.info').html(this.html);

        });

        bounds.extend(siteLatLng);

        map.fitBounds(bounds);

    }  , i * 2000); }

}


    function initialize() {

    var myOptions = {

        disableDefaultUI: true,

        mapTypeId: google.maps.MapTypeId.ROADMAP

    }

    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    setMarkers(map, markerarray);

}




当我使用setTimeout(function() {...时,出现JavaScript错误:“ markerarray未定义”。但是当我删除超时时,一切都会正常进行。但是我希望在将每个标记添加到地图时在它们之间延迟。我错过了什么?谢谢

最佳答案

这需要花点时间才能弄清楚,但这是一个很好的例子,说明有人会被抓到。问题出在i而不是markerarray

setTimeout触发时(两秒钟后),for循环已完成,并且i设置为2。因此,markers[i]markers[2],它不存在,因此markerarray(或markerarray2,为清楚起见,在我的示例中)设置为undefined

解决方案是在下面的示例中设置另一个变量c。该变量充当您的计数器,因此定义了markerarray2,因为定义了markers[c]

var markerarray = [
['Mount Evans', 39.58108, -105.63535, 4, 'This is Mount Evans.'],
['Badlands National Park', 43.785890, -101.90175, 1, 'This is Badlands National Park']
];

function setMarkers(markers) {
    var c = 0;
    for (var i = 0; i < markers.length; i++) {  setTimeout(function() {
            var markerarray2 = markers[c];
            c++;
            alert(markerarray2[0]);
        }, i * 1000);
    }
}

setMarkers(markerarray);

10-08 16:01