Answer the question
In order to leave comments, you need to log in
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
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.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question