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

115
Views
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 answers
Answer question

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 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!