简体   繁体   English

Angular 6从Google Map删除所有标记

[英]Angular 6 Remove all markers from google map

<div #gmap class="map"></div>

for (let marker of this.markersDisplay) {
          let markerColor = (marker.MarkerType == MarkerType.Ok) ? "green" : (marker.MarkerType == MarkerType.Warning) ? "yellow" : "red";
          let markerClick = new google.maps.Marker(
            {
              position: new google.maps.LatLng(marker.Latitude, marker.Longitude),
              map: this.map,
              title: marker.Title,
              visible: marker.Visible,
              clickable: marker.Clickable,
              icon: 'http://maps.google.com/mapfiles/ms/icons/' + markerColor + '-dot.png',
            });
          markerClick.addListener('click', () => { this.MarkerClick(marker); });
        }
      }

I need to filter markers on the map. 我需要过滤地图上的标记。 Before adding new I want to clean all markers from the map. 在添加新标记之前,我要清除地图上的所有标记。 How to do that? 怎么做?

How to remove all at once? 如何一次全部删除?

You can't. 你不能 Push each Marker object to an array: 将每个Marker对象推送到一个数组:

// Create empty markers array    
var markers = [];

for (let marker of this.markersDisplay) {
  let markerColor = (marker.MarkerType == MarkerType.Ok) ? "green" : (marker.MarkerType == MarkerType.Warning) ? "yellow" : "red";
  let markerClick = new google.maps.Marker({
    position: new google.maps.LatLng(marker.Latitude, marker.Longitude),
    map: this.map,
    title: marker.Title,
    visible: marker.Visible,
    clickable: marker.Clickable,
    icon: 'http://maps.google.com/mapfiles/ms/icons/' + markerColor + '-dot.png',
  });
  markerClick.addListener('click', () => {
    this.MarkerClick(marker);
  });

  // Push marker to markers array
  markers.push(markerClick);
}

Later when you want to remove them all, loop through the array and call setMap(null) on each Marker: 稍后,当您要全部删除它们时,遍历数组并在每个Marker上调用setMap(null)

for (var i=0; i<markers.length; i++) {

  markers[i].setMap(null);
}

you can try running foreach on markers and then set : 您可以尝试在标记上运行foreach,然后设置:

marker.setMap(null);
marker = null;

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

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