简体   繁体   中英

simple javascript settimeout problem

<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);

}

When i use the setTimeout(function() {... i get a javascript error: "markerarray is undefined". But when i remove the timeout everything work as it should. But i want a delay between each marker when theyre added to the map. Did i miss something? Thanks

This took a bit of figuring out but it is a very nice example of where someone can get caught. The issue lies with i not markerarray .

By the time that the setTimeout fires (after two seconds) the for loop has finished and i is set to 2. markers[i] is therefore markers[2] , which does not exist, and so markerarray (or markerarray2 , for clarity, in my example) is set to undefined .

The solution is to set up another variable, c in the example below. That variable acts as your counter and so markerarray2 is defined because markers[c] is defined.

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);

我会尝试将MarkerArray定义移至第一行,然后再进行任何操作

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM