Nemanja Andric
Nemanja Andric

Reputation: 665

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?

Upvotes: 1

Views: 2613

Answers (2)

MrUpsidown
MrUpsidown

Reputation: 22486

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

Upvotes: 2

OrDushi
OrDushi

Reputation: 96

you can try running foreach on markers and then set :

marker.setMap(null);
marker = null;

Upvotes: 0

Related Questions