简体   繁体   English

在点击谷歌地图上添加标记

[英]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.我希望能够在 map 上添加标记,仅在按下“添加标记”按钮后单击,但按钮不起作用,function 甚至在我按下按钮之前运行。 https://jsfiddle.net/snoLg0tp/ 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,
              });

Can make a flag that can be toggled with the button or in the addMarker function.可以制作一个可以用按钮或 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/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;
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM