1

I'm working on a small funny bit of code and i'm stuck.

on line 66 in the JS file. it cant define data... it is in the scope right?

please help me.

http://codepen.io/shiva112/pen/JGXoVJ

  function PlaceMarkers(data){
  for (i = 0; i < data.length - 1; ++i) {
    if (data[i].country == "NL"){  

      map.addMarker({
          lat: data[i].lat,
          lng: data[i].lng,
          title: 'Marker with InfoWindow',
          infoWindow: {content: "Station: " + data[i].name},
          click: function(e) {
            $("#info h2").remove(); 
            $("#info").append( "<h2>U hebt station " + data[i].name + " geselecteerd.</h2>" ); 
           }
      });

    }  
  }   

the append line is not working. data[i].name 2 lines above is in the scope!! but why not the data[i].name in the append line..

  • 2
    Please show the relevant portion of your code *here*. – isherwood Dec 17 '15 at 19:33
  • It's really important to post your code here and not on an external site. For one, it doesn't force people to open two windows, and secondly it means that resource won't randomly expire in the future and render this question useless. Just paste in the *minimal* example of what your problem is and you'll get a much better response rate. – tadman Dec 17 '15 at 19:34
  • Sorry, i updated the post.. – Shiva Traanman Dec 17 '15 at 19:43

2 Answers2

4

data[i].name in the click handler isn't evaluated until after the for loop has finished, and the values have changed. You can create an immediately invoked function expression to get around this:

function PlaceMarkers(data) {
  for (i = 0; i < data.length; ++i) {
    if (data[i].country == "NL") {
      (function(station) {
        map.addMarker({
          lat: station.lat,
          lng: station.lng,
          title: 'Marker with InfoWindow',
          infoWindow: {
            content: "Station: " + station.name
          },
          click: function(e) {
            $("#info h2").remove();
            $("#info").append("<h2>U hebt station " + station.name + " geselecteerd.</h2>");
          }
        });

      })(data[i]);

    }
  }
}

http://codepen.io/anon/pen/obxzmG

Jason P
  • 26,984
  • 3
  • 31
  • 45
0

Like @JasonP said, in the click handler i isn't evaluated until after the for loop has finished.

You could set a custom key name and then access it by using this.name like this:

map.addMarker({
    lat: data[i].lat,
    lng: data[i].lng,
    name: data[i].name,
    title: 'Marker with InfoWindow',
    infoWindow: {content: "Station: " + data[i].name},
    click: function(e) {
      $("#info h2").remove(); 
      $("#info").append( "<h2>U hebt station " + this.name + " geselecteerd.</h2>" ); 
    }
});

http://codepen.io/pespantelis/pen/LGNRgL

Pantelis Peslis
  • 14,930
  • 5
  • 44
  • 45