Javascript marker not working when put into an array

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?

Answers


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

Need Your Help

How to sort cells on button click, in a tableView added as subview to uiviewcontroller?

uitableview nssortdescriptor

so first I'll give some background information so you can understand my problem completely. I've spent hours looking for a solution but still can't seem to get it right. So I'm trying to create an ...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.