Reputation: 359
<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
Upvotes: 0
Views: 464
Reputation: 5157
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);
Upvotes: 3
Reputation: 7013
I would try and move the MarkerArray definition to the first line, before anything
Upvotes: 0