Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

233
Views
¿Cómo agregar un botón para ejecutar código dentro del marcador LeafletJS?

Estoy tratando de agregar un botón dentro de un puntero que imprime un registro en la consola. Esto solo pretende ser una prueba, por lo que puedo hacer que el marcador ejecute un método, pero ni siquiera puedo hacer que imprima texto.

 const marker = L.marker([latitude, longitude]).addTo(map); const button = '<br/><button type="button">Click button</button>' const clickbutton = document.querySelector("#click"); button1.addEventListener("click", function(event) { console.log('This button works!'); }); marker.bindPopup(button);

Cuando cargo la página, inmediatamente aparece este error:

No capturado (en promesa) TypeError: no se pueden leer las propiedades de nulo (leyendo 'addEventListener')

La consola dice que este error es causado por

 button1.addEventListener("click", function(event) {

pero no estoy seguro de por qué es nulo. ¿Puede alguien ayudarme?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Estás creando el botón incorrectamente.

Será justo de esta manera:

 const button = document.createElement('button'); button.id = 'delete'; button.textContent = 'Delete marker';

Para agregar un botón a la página, debe encontrar el elemento principal deseado y agregar el botón como elemento secundario:

 // replace this id with what you need const buttonParrentId = 'button-parrent-id'; const buttonParrent = document.getElementById(buttonParrentId); buttonParrent.appendChild(button);

A continuación, puede trabajar con el botón según lo necesite:

 const marker = L.marker([latitude, longitude]).addTo(map); button.addEventListener("click", function(event) { console.log('This button works!'); }); marker.bindPopup(button);

Ejemplo de código de resultado:

 const button = document.createElement('button'); button.id = 'delete'; button.textContent = 'Delete marker'; // replace this id with what you need const buttonParrentId = 'button-parrent-id'; const buttonParrent = document.getElementById(buttonParrentId); buttonParrent.appendChild(button); const marker = L.marker([latitude, longitude]).addTo(map); button.addEventListener("click", function(event) { console.log('This button works!'); }); marker.bindPopup(button);

Más sobre createElement

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!