0

The following code is running in a loop, it is simply adding HTML markers in a map and attach click event for each of the markers. Click event is attached with all the markers and I can see the alert but the popup appears with the last markers only, which means only the last marker is being passed as argument to the event.

var marker = new atlas.HtmlMarker({
  position: [long, lat],
  text: step,
  popup: new atlas.Popup({
    content: 'test',
    pixelOffset: [0, -30],
    closeButton: false
  })
});

markers.push(marker);

map.events.add('click', marker, () => {
  marker.togglePopup();
});

Can anyone please help how can we send all the markers to the event handler so the respective popups will appear when clicked on the marker?

Thanks.

3limin4t0r
  • 19,353
  • 2
  • 31
  • 52
  • Due to the line *"The following code is running in a loop"* I suspect that the issue lies outside of the shared code and is similar to [JavaScript closure inside loops – simple practical example](/q/750486/3982562). If this is indeed the case, replace `var` with `let` or `const` and your issue should be solved. – 3limin4t0r Oct 25 '22 at 13:02

1 Answers1

0

Change the code to this:

var marker = new atlas.HtmlMarker({
  position: [long, lat],
  text: step,
  popup: new atlas.Popup({
    content: "test",
    pixelOffset: [0, -30],
    closeButton: false,
  }),
});

markers.push(marker);

function addMarkerToMap(marker) {
  map.events.add("click", marker, () => {
    marker.togglePopup();
  });
}
markers.forEach(addMarkerToMap);

The problem is that your marker variable in your code is just the last instance and you are not iterating the array while adding handlers.

frankhommers
  • 1,169
  • 12
  • 26