使用1按钮切换显示/隐藏Google标记

时间:2018-05-31 08:16:26

标签: javascript google-maps-api-3 google-maps-markers

我正在尝试切换一个按钮,该按钮会隐藏/显示放置在地图中的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);

2 个答案:

答案 0 :(得分:1)

你不能做这样的事吗?

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

然后把它放在一个按钮上,你可以用你的按钮保持一个计数器,当它只做一个功能时,它是奇数做另一个?

答案 1 :(得分:0)

// 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;
    }
}

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