Reputation: 2998
I'm currently working on a website that features a Google map with my custom markers on it. Each marker has its own link, and I can easily link each marker to a URL as follows (this example has only one of my markers) -
var image = 'parkour.png';
var locations = [
new google.maps.Marker({
position: new google.maps.LatLng(43.670231, -79.386821),
map: map,
url: "http://bit.ly/RDYwKQ",
icon: image
})
]
google.maps.event.addListener(locations[0], 'click', function() {
window.location.href = locations[0].url;
});
As you can see, I am simply creating an array, adding an element, and then linking the element. This works fine. However, when I loop through each element to add a listener to each one, not a single marker has a link (they all still appear, and still cause the mouse to change as though there is a link, but clicking does nothing). Here is the code for that -
var image = 'parkour.png';
var locations = [
new google.maps.Marker({
position: new google.maps.LatLng(43.670231, -79.386821),
map: map,
url: "http://bit.ly/RDYwKQ",
icon: image
})
]
for(x in locations) {
google.maps.event.addListener(x, 'click', function() {
window.location.href = x.url;
})
}
Note that the only change is that the elements are looped through and called in this way.
I've tried everything, from changing it to a normal for-loop, to creating a marker first and then adding it to the array, and I can't seem to find any fix.
Any suggestions?
Upvotes: 0
Views: 85
Reputation: 43728
You should not use the for in
statement to loop over an array. The for in
statement iterate over all the keys of an object and yields that key. To loop over an array, use a simple for
loop instead.
Also, as a good practice, you should have a single var
statement and limit property lookups as much as possible. Additionnaly, you must be careful with closures: JavaScript closure inside loops – simple practical example
var i = 0,
len = locations.length,
addListener = google.maps.event.addListener,
l;
for(; i < len; i++) {
addListener((l = locations[i]), 'click', (function(l) {
return function () {
window.location.href = l.url;
};
})(l));
}
Upvotes: 1