Home > front end >  Adding marker on click google maps
Adding marker on click google maps

Time:02-04

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,
              });

CodePudding user response:

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;
  }
}
  •  Tags:  
  • Related