0

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?

Cisplatin
  • 2,860
  • 3
  • 36
  • 56

1 Answers1

1

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));
     }
Community
  • 1
  • 1
plalx
  • 42,889
  • 6
  • 74
  • 90
  • As mentioned in OP, I have tried this, but it fails to result in any solution. Would you happen to have any other ideas? I'm up for anything by now. – Cisplatin May 02 '13 at 00:24
  • Beautiful; any chance you know why this works, and mine doesn't? – Cisplatin May 02 '13 at 00:41
  • @Simon, have a look at the link I posted about closures ;) – plalx May 02 '13 at 00:50
  • javascript function closure. [Mike Williams' explanation from his Google Maps API v2 tutorial](http://econym.org.uk/gmap/closure.htm) – geocodezip May 02 '13 at 00:50