问题
I am trying to draw 50 markers in a row with 2 seconds in between each marker. The first marker gets drawn in GPS position (x, y) and then two seconds later, the second marker gets drawn in GPS position (x + 0.0004, y) and continues until the 50th marker is created on the map.
I have placed the marker constructor inside a setTimeout function. The setTimeout function is placed inside a for loop. However, when I run this, the loop runs through the 50 markers instantaneously (ie without the 2 second delay between each marker). Any suggestions on where I am going wrong?
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:
setTimeout is working fine. You are delaying all your markers by 2 seconds (the delay isn't between them).
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);
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);
body, html, #googleMap {
height: 100%;
width: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="googleMap"></div>
来源:https://stackoverflow.com/questions/32000569/settimeout-function-not-working-when-looping-through-markers-on-gmaps-api