Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

117
Vistas
Adding marker on click google maps

I want to be able to add marker on the map by click only after pressing the button "add marker" but the button doesn't work, the function runs even before I press the button. https://jsfiddle.net/snoLg0tp/

        <input id="add-markers" type="button" value="Add marker" />
    
        function initMap() {
          const haightAshbury = { lat: 37.769, lng: -122.446 };
        
          map = new google.maps.Map(document.getElementById("map"), {
            zoom: 12,
            center: haightAshbury,
            mapTypeId: "terrain",
          });
          // This event listener will call addMarker() when the map is clicked.
          map.addListener("click", (event) => {
            addMarker(event.latLng);
          });
      document
      .getElementById("add-markers")
        .addEventListener("click", addMarker);
        
            function setMapOnAll(map) {
              for (let i = 0; i < markers.length; i++) {
                markers[i].setMap(map);
              }
            }
            function addMarker(position) {
              const marker = new google.maps.Marker({
                position,
                map,
              });
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Can make a flag that can be toggled with the button or in the addMarker function.


let shouldAddMarker = true;

...

document
    .getElementById("add-markers")
    .addEventListener("click", addMarker => {shouldAddMarker = !shouldAddMarker});

...

function addMarker(position) {
  if (shouldAddMarker) {
    const marker = new google.maps.Marker({
      position,
      map,
    });

    markers.push(marker);
  }
}

See https://jsfiddle.net/x4twfaze/2/

If you only want to add a single marker after each button click. You can change it to:


let shouldAddMarker = false;

...

document
    .getElementById("add-markers")
    .addEventListener("click", addMarker => {shouldAddMarker = true});

...

function addMarker(position) {
  if (shouldAddMarker) {
    const marker = new google.maps.Marker({
      position,
      map,
    });

    markers.push(marker);
    shouldAddMarker = false;
  }
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda