使用 1 个按钮切换 Show/Hide Google 标记

Toggle Show/Hide Google Marker with 1 button

我正在尝试切换一个按钮,该按钮将 hide/show 放置在地图中的 google 标记。我一直在寻找关于 SOF 的答案,但都提供了数组方法。我想知道是否可以在没有数组的情况下做到这一点。

      function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
      zoom: 12,
      center: {lat: 1.3420894594991328, lng: 103.83490918886719},
    });

        var ntuc = {
        lat: 1.32805676,
        lng: 103.9216584
    };

        var ntucmap = new google.maps.Marker({
        position: ntuc,
        map: map,
        icon: 'https://maps.google.com/mapfiles/kml/paddle/blu-stars.png'
    });

   }

      function toggleNTUCmap() {
    if (!ntucmap.getVisible()) {
        ntucmap.setVisible(true);
    } else {
        ntucmap.setVisible(false);
    }
  }

按钮

<button class="button-oj pure-button" onclick="toggleNTUCmap()">
          <i class="fas fa-hospital"></i> NTUC</button>

对于函数toggleNTUCmap(),我已经尝试了以下方法,但还是不行。

ntucmap.setMap(ntucmap.getMap() ? null : map);

你不能做这样的事情吗?

    function clearMap(map) {
    for(var i = 0; i<ntucmap.length; i++){
      ntucmap[i].setMap(null);
    }
  }

以及演出部分

function setMapOnAll(map) {
    for (var i = 0; i < ntucmap.length; i++) {
      ntucmap[i].setMap(map);
    }
}

然后将它放在一个按钮中,你可以用你的按钮保持一个计数器,当它甚至执行一个功能时,当它奇怪时执行另一个?

// Adds a marker at the center of the map.
var ntuc = {lat: 1.32805676, lng: 103.9216584};
addMarker(ntuc);
setMapOnAll(null);

// Adds a marker to the map and push to the array.
function addMarker(location) {
    var marker = new google.maps.Marker({
        position: location,
        map: map,
        icon: 'https://maps.google.com/mapfiles/kml/paddle/blu-stars.png'
    });
    markers.push(marker);
}

// Sets the map on all markers in the array.
function setMapOnAll(map) {
    for (var i = 0; i < markers.length; i++) {
        markers[i].setMap(map);
    }
}

// Show/Hide Markers
var counter = 0;

function toggleMarkers() {
    if (counter == 0) {
        setMapOnAll(map);
        counter = 1;
    } else {
        setMapOnAll(null);
        counter = 0;
    }
}

最后我用数组保存了所有的标记。根据用户用来切换的按钮,它会决定它的标记是否显示在地图上。