0

I build a table with rows made by the inputs from a form. I have an input field for address( autocomplete with google maps api). I have an array with markers on the map and an array with all the tr (from the body of the table). I am trying to put an eventListener on the tr (onclick) to center the map on the corresponding marker. The index on both array corresponds (0 position on the marker array represents the tr that contains that address on the map)

tableTr = tableBody.getElementsByTagName("tr");


for (w = 0; w < tableTr.length; w++) {
  tableTr[w].addEventListener("click", function () {        
      map.setCenter(markers[w].getPosition())
  });
}

I have no errors but when I click nothing happens!!!

wogsland
  • 9,106
  • 19
  • 57
  • 93
Florin
  • 9
  • 3

1 Answers1

0

In your for...loop, the event listener is a closure (notice w is defined outside the event listener function). When the event listener is called, it will get the value of variable w, which is tablet.length rather than the value when the event listener was added. To solve the issue, you can create a function that creates the event listener:

function getEventListener(idx) { return function() {
    map.setCenter(markers[idx].getPosition());
})

In your for loop, add the event listener by calling the function like this:

tableTr[w].addEventListener("click", getEventLisener(w));