简体   繁体   中英

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:

// 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:

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

  markers[i].setMap(null);
}

you can try running foreach on markers and then set :

marker.setMap(null);
marker = null;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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