Skip to content
Advertisement

How can i click my html (DOM) and open an existing popup on my Leaflet Map. Im only using Vanilla JS

Im trying to conect my “See in map” (html) with my map and open a popUp that is already created (i click on the map and the popups open).

i know i have to use something like

L.DomEvent.on(tiendas,'click',function(e){
   console.log('Button clicked')
});

but i dont know how to do it. Can anyone help me? Thank you!

enter image description here

enter image description here

Advertisement

Answer

I see that all of your links have the same id="tiendanombre" attribute – is this intentional (id attributes should be unique on the page)?

According to this answer How to open leaflet marker popup from link outside of map? the marker has an openPopup() method that we need to call

In your HTML template is there a way that we can identify which entry in your diet array the link refers to? Is the HTML generated from the same array maybe?

If we can get an identifier into the HTML, for example

<a href="#" class="icon-link" data-diet-id="{Identifier that also appears in diet array}">Open in map</a>

Then we can look for that link when we are in your forEach loop, after you have made your marker

const marker = new L.marker(diet[i][0], diet[i][1]).bindPopup(etc etc);

// We need to find the link that corresponds to this marker.
// if the HTML was generated from the same diet array this will be quite simple,
// because it will be in the same position in the list of '.tiendaNombre a.icon-link' elements

// const link = document.querySelectorAll('.tiendaNombre a.icon-link')[i]

// otherwise if we have added an identifier to our HTML then we will need to find our link using that
const selector = `a[data-diet-id="${diet[i][IndexOfTheIdentifierField]}"]`;
const link = document.querySelector(selector);

// once we have found our link we just need to tell it what to do when it gets clicked
if(link) {
  link.addEventListener('click', ()=>{
   marker.openPopup(); 
  })
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement