0

I've seem to run into an issue, i saw a lot of implementations of the infobox but cant seem to figure out how to insert another piece of code onto a marker. I'm quite unexperienced with javascript so i can't seem to figure it out.

When i go to the maps it shows all the markers but only selects the piece of code that is the last in the array,

code :

    function updateMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 4,
    center: locationarray[0]
  });
  var markernumber = new Array();
  for (var i = 0; i < 99; i++) {
    markernumber[i] = new google.maps.Marker({
      position: locationarray[i],
      map: map
    });
    console.log('in loop:' + i);
    google.maps.event.addListener(markernumber[i], 'click', function() {
      console.log('in click:' + i);
      openInNewTab(contentString[i]);
    });
  }
  document.getElementById('loader').style = "opacity: 0;";
}

contentstring[i] is working fine, so it's nothing outside of this function.

CosmicS
  • 13
  • 3
  • 1
    `Google maps apiv3 gives every marker the same click function` - no, you are doing that ... `i` inside the event handler will be 100 for every marker click. think closure – Jaromanda X Oct 19 '17 at 10:20
  • 1
    possible duplicate of [Google Maps JS API v3 - Simple Multiple Marker Example](https://stackoverflow.com/questions/3059044/google-maps-js-api-v3-simple-multiple-marker-example) – geocodezip Oct 19 '17 at 13:14

1 Answers1

-1

Try something like that:

var markernumber = new Array();
    for (var i = 0; i < 4; i++) {
        markernumber[i] = new google.maps.Marker({
            position: position[i],
            map: map
        });
        console.log('in loop:' + i);
        (function (i, content, marker) {

            google.maps.event.addListener(marker, 'click', function (e) {
                console.log('in click:' + i);
                //console.log(e);
            });

        })(i, contentString[i], markernumber[i]);
    }

You have got an closure's error. It means that when the listener will be executed, the i value has already change (into the for) and it pass to 99.

Explain in an order way. When you call i, or what ever variable you want, the system will try to find the last value with this name. So, if the value change, the result will be the last "update" of the variable.

Here, when you try to read i you have ever "update" i in the for so the last value will be 99.

If you want to read the value of i in your listener, you have to create an IIFE and pass in the parameter the actual value of i, contentString and markernumber.

Consult the documentation if you want more details about closures or here about IIFE (you have to find a bit in the documentation but there is a passage in it. It is the best like and can find).

Tell me if you have some questions

SphynxTech
  • 1,799
  • 2
  • 18
  • 38