J
J
javax2011-01-29 16:17:58
JavaScript
javax, 2011-01-29 16:17:58

Javascript: function execution context

I make a cycle to hang InfoWindow display listeners on the markers of Google maps. As a result, when you click on the marker, it is always shown for the last point. Those. it seems that the function is not created in its own context (as I used to in Java), but the last point value from the loop is used. How does it work in JavaScript? What should I do so that the listener for each marker shows the InfoWindow in the correct place? Thanks

 for (var i = 0; i < points.length; i++) {


      var point = points[i];
      var myLatLng = new google.maps.LatLng(point.lat, point.lng);
      var marker = new google.maps.Marker({
          position: myLatLng,
          map: map,
          icon: point.icon,
          title: point.name,
          visible:false
      });
        google.maps.event.addListener(marker, 'click', function() {
              infowindow.setContent(point.description);
              infowindow.setPosition(myLatLng);
              infowindow.open(map);
        });

      point.marker = marker;
    }







Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
marcus, 2011-01-29
@marcus

You have a closure at point. We need to move the addition of the listener to a separate function with one argument, which is called in a loop and passed the pointer there.

[
[email protected]><e, 2011-01-29
@barmaley_exe

javascript.com/closure

E
Eugene, 2011-01-29
@Methos

It is necessary to place everything inside the loop inside the function and call it:
(function() {
//…
})();
Then for each element of the cycle there will be its own environment.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question