B
B
Barrakuda742016-10-24 18:05:00
JavaScript
Barrakuda74, 2016-10-24 18:05:00

How does assigning handlers inside for work?

Guys, please tell me the algorithm of the code inside the for loop.
The Google Maps website has an example of placing several markers, each with its own information. window.
This code works fine, adds 5 markers to the def. area, each has its own handler with its own information. window. In the example, for some reason, they pull out the function for creating info windows from initMap. And it’s not clear to me why, when I try to paste back just this code into initMap, 5 markers also appear, but when I click on any of them, information opens. window just above the last marker. Where is the wrong section in the for loop?
Here I just removed the external attachSecretMessage function, and I don’t understand where the plug is due to this, because the logic of the code essentially remained the same:

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 5,
    center: {lat: -25.363882, lng: 131.044922 }
  });

  var bounds = {
    north: -25.363882,
    south: -31.203405,
    east: 131.044922,
    west: 125.244141
  };
  map.fitBounds(bounds);
  
  var secretMessages = ['This', 'is', 'the', 'secret', 'message'];
  var lngSpan = bounds.east - bounds.west;
  var latSpan = bounds.north - bounds.south;
  for (var i = 0; i < secretMessages.length; ++i) {
    var marker = new google.maps.Marker({
      position: {
        lat: bounds.south + latSpan * Math.random(),	
        lng: bounds.west + lngSpan * Math.random()
      },
      map: map
    });
    var infowindow = new google.maps.InfoWindow({
      content: secretMessages[i]
    });
    marker.addListener('click', function() {
      infowindow.open(marker.get('map'), marker);
    });
  }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
Barrakuda74, 2016-10-25
@Barrakuda74

Thank you very much oxidmod ! Your code worked just fine. It finally came to my mind that I messed up on the logic of the closure inside the loop and the scope of the variables. By the way, in addition to encapsulating the entire loop code with an anonymous self-calling function, there is a second solution to the problem, this is declaring the infowindow and marker variables with the keyword letinstead of var.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question